开发者

Can get members, but not count of NSMutableArray

I'm filling an NSMutableArray from a CoreData call. I can get the first object, but when I try to get the count, the app crashes with Program received signal: “EXC_BAD_ACCESS”. How can I get the count?

Here's the relevant code - I've put a comment on the line where it crashes.

- (void)viewDidLoad {
[super viewDidLoad];

managedObjectContext = [[MySingleton sharedInstance] managedObjectContext];

if (managedObjectContext != nil) {
    charactersRequest = [[NSFetchRequest alloc] init];
    charactersEntity = [NSEntityDescription entityForName:@"Character" inManagedObjectContext:managedObjectContext];
    [charactersEntity retain];
    [charactersRequest setEntity:charactersEntity];
    [charactersRequest retain];

    NSError *error;
    characters = [[managedObjectContext executeFetchRequest:charactersRequest error:&error] mutableCopy];
    if (characters == nil)开发者_如何学Python {
        NSLog(@"Did not get results for characters: %@", error.localizedDescription);
    }
    else {          
        [characters retain];            
        NSLog(@"Found some character(s).");
        Character* character = (Character *)[characters objectAtIndex:0];
        NSLog(@"Name of first one: %@", character.name);
        NSLog(@"Found %@ character(s).", characters.count);  // Crashes on this line with - Program received signal:  “EXC_BAD_ACCESS”.
    }
}

}

And previous declarations from the header file:

@interface CrowdViewController : UITableViewController {
NSManagedObjectContext *managedObjectContext;
NSFetchRequest *charactersRequest;
NSEntityDescription *charactersEntity;
NSMutableArray *characters;

}

I'm a bit perplexed and would really appreciate finding out what is going on.


Count is an integer so, you should have used %d when using it with NSLog

NSArray Reference


The cash is caused because count is a method, not an property, of NSArray so you can't use the dot notation to call it. You have to use bracket notation thusly:

 NSLog(@"Found %d character(s).", [characters count]);

It's an easy mistake to make if you've worked in a lot of languages that do use dot notation to call methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜