开发者

Problem with class methods in objective c

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 '+ret开发者_如何学运维urnselectedindex'

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:

[selectedindex release];
selectedindex = [[NSString stringWithFormat:@"%d", indexPath.row] retain];

That will fix your crash.

Now that your crash is fixed, though, you should really rethink your design. There's no reason for selectedindex to be a global variable; since the selected index is very likely specific to that instance of your ContactsController, it should be an instance variable of that class. Instead, you've declared it as a global variable, which means that there is only one selectedIndex shared between ALL instances of ContactsController. Then, in turn, your +returnselectedindex method 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.)


I think You didn't allocated the selectedindex NSString.Thats why it will not crash on the same class and it crashes in the new Class. So You allocate it in the setter method of "returnselectedindex" Otherwise, Copy or retain the receive value of returnselectedindex value like this,

selected = [[ContactsController returnselectedindex]copy];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜