如何使用ARC处理iOS中的自动释放对象

时间:2013-03-19 09:23:33

标签: iphone ios objective-c nsmutablearray autorelease

我正在创建一个启用了ARC的iPhone应用程序,因此我遇到了这种情况。

在应用程序的每个页面中,都会发生Web服务调用。在这个方法中,我在从服务器添加新值之前从数组中删除所有对象。一切正常,但有时app会在[self.myArray removeAllObjects]崩溃。

我为myArray @property (strong, nonatomic) NSMutableArray myArray;

设置了@property

我在想的是,当我使用ARC时,对象myArray在某个时刻被释放,我尝试从同一个数组中删除所有对象。导致崩溃,我不确定,但我没有看到任何其他原因。

所以,在我删除其中的对象之前,我正在考虑检查数组是否有效。我写了一个示例代码来检查不同的场景。这是:

NSMutableArray *testArray = [[NSMutableArray alloc]initWithObjects:@"1", @"2", @"3", @"4", nil];

if (testArray) {
    NSLog(@"i am alive");
}

[testArray release];

if (testArray) { //here how to check whether this array is valid or not?
    NSLog(@"i am alive: %@", testArray);
}else{
    NSLog(@"I am dead");
    testArray = [[NSMutableArray alloc]initWithObjects:@"5", @"6", @"7", @"8", nil];
}

[testArray release];
[testArray removeAllObjects];

我知道它会导致崩溃,但它只是用于检查。在这里,我该如何检查数组是否有效?这是正确的方法还是别的什么?

请指导我。
感谢。

实际代码:

- (void)getFriendsList{

    BOOL netIsAvailable = [self connected];

    if (netIsAvailable) {
        @try {
            NSString *accessToken = [self getAccessToken];
            NSString *tokenEncoded = [accessToken stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            NSString *finalUrl = [NSString stringWithFormat:@"%@FriendsnSongs/%@",CommonWebServiceUrl,tokenEncoded];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:finalUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
            NSURLResponse *response = nil;
            NSError *error = nil;
            NSData *currentResult = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//            NSString* responseString = [[NSString alloc] initWithData:currentResult encoding:NSUTF8StringEncoding];

            if (currentResult != nil) {
                NSDictionary* json = [NSJSONSerialization
                                      JSONObjectWithData:currentResult
                                      options:kNilOptions
                                      error:&error];
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                int statusCode = [httpResponse statusCode];

                NSMutableArray *match = [json valueForKey:@"FriendsnSongsResult"];
                if (statusCode == 200) {
                    if (self.userGuidArray) {
                        [self.albumNameArray removeAllObjects];  //here got crash
                        [self.artistNameArray removeAllObjects];
                        [self.deviceNameArray removeAllObjects]; //here also got crash once
                        [self.nickNameArray removeAllObjects];
                        [self.userProfileImageArray removeAllObjects];
                        [self.songTitleArray removeAllObjects];
                        [self.songStatusArray removeAllObjects];
                        [self.userGuidArray removeAllObjects];
                    }

                    for(NSArray *player in match) {
                        [self.albumNameArray addObject:[(NSArray *)player valueForKey:@"AlbumName"]];
                        [self.artistNameArray addObject:[(NSArray *)player valueForKey:@"Artist"]];
                        [self.nickNameArray addObject:[(NSArray *)player valueForKey:@"NickName"]];
                        [self.userProfileImageArray addObject:[(NSArray *)player valueForKey:@"ProfileImage"]];
                        [self.songStatusArray addObject:[(NSArray *)player valueForKey:@"Status"]];
                        [self.songTitleArray addObject:[(NSArray *)player valueForKey:@"Title"]];
                        [self.userGuidArray addObject:[(NSArray *)player valueForKey:@"UserGuid"]];
                        [self.deviceNameArray addObject:[(NSArray *)player valueForKey:@"DeviceName"]];
                    }
                    //Start timer for updating the friends list
                    if (timerActivated)
                        [self performSelectorOnMainThread:@selector(backgroundFriendsListUpdate) withObject:nil waitUntilDone:NO];
                    //Update table if the table not in search mode
                    if (!isSearching)
                        [self performSelectorOnMainThread:@selector(updateTable) withObject:nil waitUntilDone:YES];
                }
            }
        }
        @catch (NSException *exception) {
            NSLog(@"Exception: %@",exception.name);
        }
    }
    [DejalActivityView removeView];
}

重要的是,在这个类中,后台线程每30秒运行一次。它将调用相同的方法来刷新表。

2 个答案:

答案 0 :(得分:4)

如果您使用ARC,请从代码中移除[testArray release];这一行,因为 ARC会处理。否则[testArray release];写入-(void)dealloc方法。

在删除数组值之前给出条件

if(myArray.count > 0)// because sometime it is good logic for us.
  [myArray removeAllObjects];

然后在myArray中插入数据。

答案 1 :(得分:1)

正如您在评论中所建议的,使用临时数组是一个好主意。以下代码将填充临时数组并使用它来替换主线程中的数组。

NSMutableArray *tempAlbumArray = [NSMutableArray array];
//fill your array
[tempAlbumArray addObject:<#some object#>];
dispatch_async(dispatch_get_main_queue(), ^{
    //replace your array with the new one
    //this code will be executed in main thread
    self.albumNameArray = tempAlbumArray;
});