i have a tableview controller like so,
NSString *selectedindex;
@interface ContactsController : UITableViewController<ABPeoplePickerNavigationControllerDelegate> {
NSMutableArray *names;
NSMutableArray *phonenumbers;
NSMutableArray *contacts;
DatabaseCRUD *sampledatabase;
}
+(NSString *) returnselectedindex;
@end
in the implementation file i have
+(NSString *) returnselectedindex
{
return selectedindex;
}
when a row is selected in the tableview i put have the following code.
selectedindex = [NSString stringWithFormat:@"%d", indexPath.row];
NSLog(@"selected row is %@",selectedindex);
in a different class i am trying to access the selectedindex. like so
selected = [ContactsController returnselectedindex];
NSLog(@"selected is %@",selected);
it gives me a warning: 'ContactsController' may not respond to '+returnselectedindex'
and crashes. i am not sure why. i have used class methods previously lot of times , and never had a problem. any help please. Thank You.
The reason you’re crashing is that you’re assigning a value to a global variable (
selectedindex), but you’re never taking ownership of it by calling-retain. As a result, the string doesn’t know you need it to stay around, so the system deallocates it. Later, when you try to access it, it’s already deallocated.In order to avoid the crash, you need to add a retain call when you assign the value. Of course, since a selected index is something that’s likely to be changing often, you’d want to release the previous value before overwriting it and retaining the new one. Thus, you should have this code:
That will fix your crash.
Now that your crash is fixed, though, you should really rethink your design. There’s no reason for
selectedindexto be a global variable; since the selected index is very likely specific to that instance of yourContactsController, it should be an instance variable of that class. Instead, you’ve declared it as a global variable, which means that there is only oneselectedIndexshared between ALL instances ofContactsController. Then, in turn, your+returnselectedindexmethod should be an instance method, not a class method. (It should also be renamed in order to follow Cocoa naming conventions, but that’s well off topic.)