componentsJoinedByString gives me EXC_BAD_ACCESS

2019-09-05 17:25发布

问题:

I have an NSMutableArray i am trying to convert into a string.
Declaring my NSMutableArray...

    NSMutableArray *listData;  

And later inside a method...

NSString *foo = [listData componentsJoinedByString:@"|"];  
NSLog(@"%@",foo);  

It seems no matter what i try i keep getting EXC_BAD_ACCESS.
To make sure each element in my array was an NSString i also tried this...

NSMutableArray *mArray = [[NSMutableArray alloc] init];  
for (id ln in listData) {  
    NSString *boo = [NSString stringWithFormat: @"%@",ln];  
    [mArray addObject:boo];  
}  
NSString *foo = [mArray componentsJoinedByString:@"|"];  
NSLog(@"%@",foo);  

I can manipulate my NSMutableArray by adding/deleting objects in the same method or other methods inside my class. But when i try "componentsJoinedByString" the error pops up. Does anyone have any advice or another way i can combine this array into a single NSString?

回答1:

In the code you've given, there will never be an NSMutableArray for listData. At some point in your code, you'll need to create one, and presumably populate it.

Edit Okay, so you may get into memory management problems here, so let's be a bit clearer:

You're synthesizing getters and setters for the instance variable, so it's good practice to use those to access it, they'll take care of retain and releasing appropriately.

To set listData you can simply use

self.listData = [listManage getList:[[NSUserDefaults standardUserDefaults] stringForKey:@"list_name"] list:@"LIST"]; 

or

[self setListData:[listManage getList:[[NSUserDefaults standardUserDefaults] stringForKey:@"list_name"] list:@"LIST"]];

if you prefer.