Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 目标c中的类方法问题_Iphone_Objective C - Fatal编程技术网

Iphone 目标c中的类方法问题

Iphone 目标c中的类方法问题,iphone,objective-c,Iphone,Objective C,我有一个这样的tableview控制器 NSString *selectedindex; @interface ContactsController : UITableViewController<ABPeoplePickerNavigationControllerDelegate> { NSMutableArray *names; NSMutableArray *phonenumbers; NSMutableArray *contacts; Data

我有一个这样的tableview控制器

NSString *selectedindex;
@interface ContactsController : UITableViewController<ABPeoplePickerNavigationControllerDelegate> {
    NSMutableArray *names;
    NSMutableArray *phonenumbers;
    NSMutableArray *contacts;
    DatabaseCRUD *sampledatabase;   
}

+(NSString *) returnselectedindex;
@end
在tableview中选择一行时,我输入以下代码

selectedindex = [NSString stringWithFormat:@"%d", indexPath.row];
NSLog(@"selected row is %@",selectedindex);
在另一个类中,我尝试访问selectedindex。像这样

selected = [ContactsController returnselectedindex];
NSLog(@"selected is %@",selected);
它给了我一个警告:
“ContactsController”可能不会响应“+returnselectedindex”


和崩溃。我不知道为什么。我以前使用过很多次类方法,从来没有遇到过问题。请帮忙。谢谢。

我认为您没有分配selectedindex NSString。这就是为什么它不会在同一个类上崩溃,也不会在新类中崩溃。 因此,您可以在setter方法“returnselectedindex中分配它 否则,复制或保留返回的selectedIndex的接收值,如下所示:

selected = [[ContactsController returnselectedindex]copy];

崩溃的原因是您正在为全局变量赋值(
selectedindex
),但您从未通过调用
-retain
获得它的所有权。因此,字符串不知道您需要它留在周围,因此系统将其释放。稍后,当您尝试访问它时,它已被解除分配

为了避免崩溃,您需要在分配值时添加retain调用。当然,由于选定的索引可能会经常更改,因此您可能希望在覆盖之前释放先前的值并保留新的值。因此,您应该具有以下代码:

[selectedindex release];
selectedindex = [[NSString stringWithFormat:@"%d", indexPath.row] retain];
那将修复你的崩溃


现在你的崩溃已经修复了,你应该重新考虑你的设计。没有理由将
selectedindex
作为全局变量;由于所选索引很可能特定于您的
ContactsController
的实例,因此它应该是该类的实例变量。相反,您将其声明为一个全局变量,这意味着
ContactsController的所有实例之间只有一个
selectedIndex
共享。然后,反过来,您的
+returnselectedindex
方法应该是实例方法,而不是类方法。(为了遵循Cocoa命名约定,它也应该重新命名,但这与主题无关。)

它修复了崩溃问题,我得到了所需的输出,但我仍然拥有它曾经崩溃的黄色警戒线。我以后再看。谢谢你的帮助。非常感谢。
[selectedindex release];
selectedindex = [[NSString stringWithFormat:@"%d", indexPath.row] retain];