addObject: массив не работает (массив все еще ноль) - PullRequest
0 голосов
/ 19 декабря 2011

Это приложение представляет собой табличное представление с контроллером панели вкладок.Я записываю счетчик массива: arrayOfFavourites, и хотя я добавляю объект, он по-прежнему имеет нулевое значение, мой связанный код, все показанные объекты размещены и инициализированы в коде (предыдущем или настоящем), некоторые являются экземплярами, а некоторые -свойства:

ListViewController.m:

  -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSLog(@"TOUCHED CELL!");

// Push the web view controller onto the navigation stack - this implicitly 
// creates the web view controller's view the first time through
[[self navigationController] pushViewController:webViewController animated:YES];

// Grab the selected item
entry = [[channel items] objectAtIndex:[indexPath row]];

if (!entry) {
    NSLog(@"!entry");
}

// Construct a URL with the link string of the item
NSURL *url = [NSURL URLWithString:[entry link]];

// Construct a request object with that URL
NSURLRequest *req = [NSURLRequest requestWithURL:url];

  // Load the request into the web view 
[[webViewController webView] loadRequest:req];

// Take the cell we pressed
// IMPORTANT PART
CELL = [tableView cellForRowAtIndexPath:indexPath];

[webViewController setItem:entry];

webViewController = nil;
webViewController = [[WebViewController alloc] init];
[entry release];

  }

WebViewController.m:

Вы трясете любимую ячейку

 -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {

cellToPassOn = nil;

NSLog(@"Favouriting"); // YES I KNOW SPELLING

// This is pretty simple, what we do is we take the cell we touched and take its title and link 
// then put it inside an array in the Favourites class

Favourites *fav = [[Favourites alloc] init];
ListViewController *list = [[ListViewController alloc] init];
[self setCellToPassOn: [list CELL]];

if (!item) {
    NSLog(@"NILLED ITEM");

}

[[fav arrayOfFavourites] addObject:[item autorelease]];
[fav setCell: cellToPassOn];
[fav release];
[list release];
item = nil;

 }

Favourites.m:

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  {

arrayOfFavourites = [[NSMutableArray alloc] init];


NSLog(@"ROWS NO.");
NSLog(@"%i", [arrayOfFavourites count]);

return [arrayOfFavourites count];
}

Ответы [ 4 ]

2 голосов
/ 19 декабря 2011

Почему вы инициализируете массив в tableview:numberOfRowsInSection?Это приведет к сбросу массива при каждой перезагрузке представления таблицы.Это может быть вашей проблемой.

0 голосов
/ 21 декабря 2011
 -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
 cellToPassOn = nil;
 NSLog(@"Favouriting"); // YES I KNOW SPELLING
 // HERE creation of a Brand NEW empty Favourites instance
 Favourites *fav = [[Favourites alloc] init];
 // HERE creation of a Brand NEW empty ListViewController instance
 ListViewController *list = [[ListViewController alloc] init];
 // HERE we hope that the ListViewController as CELL other then nil when it is Brand NEW
 [self setCellToPassOn: [list CELL]];

 if (!item) {
     NSLog(@"NILLED ITEM");
 }

 [[fav arrayOfFavourites] addObject:[item autorelease]];
 [fav setCell: cellToPassOn];
 [fav release];
 // HERE the fav instance get deallocated and don't exist anymore
 [list release];
 // HERE the list instance get deallocated and don't exist anymore
 item = nil;
 }

В этом коде list и fav существуют только в теле этого метода, попытка получить значение, к которому они относятся, будет неудачной, поскольку list и fav не существует вне этого способ.

0 голосов
/ 19 декабря 2011

Вы можете выделить arrayOfFavorites в tableView:numberOfRowsInSectionMethod, но затем вам сначала нужно проверить, равен ли он нулю.

if( !arrayOfFavorites )
    arrayOfFavoriges = [[NSMutableArray alloc] init];

Затем вы должны освободить его в методе dealloc: [arrayOfFavorites release].

0 голосов
/ 19 декабря 2011

Вы выделяете свой массив в -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

попробуйте выделить его где-нибудь еще.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...