我相信在学习过程中,下面的代码段对我来说不是很清楚。我知道一个alloc语句会增加保留数量,但是iOS开发的某些方面仍然让我感到困惑。有人可以向我解释为什么我需要在以下代码段中保留声明吗?
为什么在以下代码段中需要:[jokesArray retain];
?
我有一个jokesArray = [[NSArray alloc]init];
从我已经阅读的是足以保留?
有人可以用简单易懂的方式解释为什么需要保留声明吗? (否则应用程序崩溃与一个EXC_BAD_ACCESS。
我有一些善良的人们试图解释,但没有奏效。任何帮助,将不胜感激。
#import "JokesViewController.h"
@implementation JokesViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
jokesArray = [[NSArray alloc]init];
[self getJokes];
}
- (void)viewDidUnload
{
[super viewDidUnload];
[jokesArray release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jokesArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[[cell textLabel]setText:[[jokesArray objectAtIndex:0]objectForKey:@"text"]];
// [[cell textLabel]setText:@"ok"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
}
#pragma mark - Custom Functions
-(void) getJokes
{
NSURL *url = [NSURL URLWithString:@"someurl"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
// Use when fetching text data
NSString *responseString = [request responseString];
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
jokesArray = [resultsDictionary allValues];
[jokesArray retain]; //WHY DO I NEED THIS?
[self.tableView reloadData];
NSLog(@"%@", [jokesArray description]);
// Use when fetching binary data
// NSData *responseData = [request responseData];
}];
[request setFailedBlock:^{
NSError *error = [request error];
}];
[request startAsynchronous];
}
@end
你是怎么声明笑话数组的? – user523234