2012-04-05 56 views
0

荫得到一个EXC_BAD_ACCESS所有的时间,我想不通为什么...Objective-C的初学者:吸气二传手概率和EXC_BAD_ACCESS错误

简单的任务:

解析类pases XML与touchXML在NSMutableArray调用listArray。 在方法grabCountry我可以访问listArray和listArray.count效果很好。

现在我需要在另一个类MasterViewController中的listArray.count。 但我一直得到一个EXC_BAD_ACCESS错误。 请帮忙!

下面是代码snipplet: Parser.h

#import <Foundation/Foundation.h> 

@interface Parser : NSObject 

@property (strong, retain) NSMutableArray *listArray; 
@property (strong, retain) NSURL *url; 

-(void) grabCountry:(NSString *)xmlPath; 
@end 

Parser.m

#import "Parser.h" 
#import "TouchXML.h" 

@implementation Parser 
@synthesize listArray; 
@synthesize url; 

-(void) grabCountry:(NSString *)xmlPath { 

    // Initialize the List MutableArray that we declared in the header 
    listArray = [[NSMutableArray alloc] init]; 

    // Convert the supplied URL string into a usable URL object 
    url = [NSURL URLWithString: xmlPath]; 

    //XML stuff deleted 

    // Add the blogItem to the global blogEntries Array so that the view can access it. 
    [listArray addObject:[xmlItem copy]]; 

    //works fine 
    NSLog(@"Amount: %i",listArray.count); 
} 

@end 

MasterViewController.h

#import <UIKit/UIKit.h> 
#import "AppDelegate.h" 
#import "TouchXML.h" 
#import "Parser.h" 

@class Parser; 

    @interface MasterViewController : UITableViewController{ 

    Parser *theParser; 

} 
@end 

MasterViewControlelr.m

- (void)viewDidLoad 
{ 
NSString *xmlPath = @"http://url/to/xml.xml"; 

theParser = [[Parser alloc] init]; 
//Starts the parser 
[theParser grabCountry:xmlPath]; 

//Here I want to access the Array count, but getting an BAD ACCESS error 
NSLog(@"Amount %@",[theParser.listArray count]); 

[super viewDidLoad]; 
} 

任何人都可以解释我这里的问题是什么? 谢谢!

回答

1

在内部,每个@property都有相应的实例变量。

在你-grabCountry方法,则需要直接访问实例变量的声明listArray = [[NSMutableArray alloc] init];(与url = [NSURL URLWithString: xmlPath];相同),而不是@property的setter方法,使你alloc-initNSMutableArray倒是不酒店所保留。要调用@property的setter方法,你应该叫

NSMutableArray *temp = [[NSMutableArray alloc] init]; 
self.listArray = temp; // or [self setListArray:temp]; 
[temp release]; 

如果你想拥有的Xcode显示,当你直接访问的@property的实例变量的错误,你可以有@synthesize listArray = _listArray,改变名称实例变量为_listArray

通常,如果有alloc-init,则必须有相应的release(除非使用自动引用计数)。


此外,在[listArray addObject:[xmlItem copy]];声明,是不是需要copy的号召,为NSArray小号保留被添加到他们的每一个对象。调用copy也会增加保留计数,这是另一次泄漏。相反,你应该只是[self.listArray addObject:xmlItem];


你是因为在NSLog(@"Amount %@",[theParser.listArray count]);,您使用%@格式说明,这是NSString小号获得EXC_BAD_ACCESS。你想打印数组的数量,一个整数,所以你应该使用%d%i

+0

感谢您的回复。我改变了一切,这听起来似乎对我来说:)但是,当Iam试图访问它时,我得到了同样的错误:[theParser.listArray count](从MasterViewController类) – Nico 2012-04-06 00:17:55

+0

最后发现问题...您正在使用'%@ '当打印count(一个整数)时,你应该使用'%d'或'%i'。我通常也会被抓住。 =)我编辑了我的答案以反映这一点。 – neilvillareal 2012-04-06 00:31:42

+0

%我工作...复制和粘贴错误: - /你做了我的一天! – Nico 2012-04-06 00:33:31