分配给'readonly'返回结果...全局NSString

时间:2012-08-07 21:57:48

标签: iphone ios ipad readonly read-write

所以我拥有的是一个我希望能够在另一个类中访问的NSString。在我的RootViewController.h中,我有:

@interface RootViewController : UITableViewController

+(NSMutableString*)MY_STR;

@property (nonatomic, readwrite, retain) NSString *MY_STR;

@end

在我的RootViewController.m中:

static NSString* MY_STR;

@synthesize MY_STR;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //The NSDictionary and NSArray items (listOfItems, etc.) are called at top so don't worry about them

    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"MovieTitles"];
    MY_STR = [array objectAtIndex:indexPath.row];

}

+(NSString*)MY_STR{
    return MY_STR;
}

- (void)dealloc {
    [MY_STR release];
    [super dealloc];
}

现在在我的NewViewController类中,我想写入NSString MY_STR所以在我的.m中我有:

#import "RootViewController.h"

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"MovieTitles"];
    [RootViewController MY_STR] = [array objectAtIndex:indexPath.row];
}

但是就这一行:

[RootViewController MY_STR] = [array objectAtIndex:indexPath.row];

我收到此错误: “分配给'readonly'不允许使用objective-c消息的返回结果”

任何帮助都会非常棒!谢谢!

1 个答案:

答案 0 :(得分:0)

属性名称需要以小写字符开头。按照惯例,所有大写名称都是“#sninition”。请尝试“myStr”。

所以这一行是你的问题:

[RootViewController MY_STR] = [array objectAtIndex:indexPath.row];

左手边只是返回一个值而不是左值。你需要做的是添加

+(void) setMyStr:(NSString*)str
{
   myStr = str; // assumes ARC
}

然后

[RootViewController setMyStr:[array objectAtIndex:indexPath.row]];

您可能尚未获得Key Value Coding或属性,但为了方便ObjectiveC使用命名约定来执行这些操作。所有ivars都应以小写字母开头,原因是setter使用变量名称,首字母大写,并以“set”为前缀。因此,使用“myStr”作为变量名称(良好的CamelCase示例,再次是Apple方式),您有一个“setMyStr:”的setter。现在在你的情况下,你只在类中使用这两个方法,你可以真正使用你想要的任何方法名称 - 但它很适合实践。当你使用属性,并让编译器为你合成getter和setter时,它看起来完全如上所示。

相关问题