Existing ivar 'title' for unsafe_unretained property 'title' must be __unsafe_unretained

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

I'm just getting to grips with Objective-C 2.0

When I try to build the following in Xcode it fails. The error from the compiler is as follows:

Existing ivar 'title' for unsafe_unretained property 'title' must be __unsafe_unretained.

// main.m #import  #import "Movie.h" int main (int argc, const char * argv[]){     Movie *movie = Movie.new;      NSLog(@"%@", movie);      return 0; }  // movie.h #import   @interface Movie : NSObject{     NSString *title;     int year;     int rating; }  @property(assign) NSString *title; @property(assign) int rating; @property(assign) int year;  @end  #import "Movie.h"  @implementation Movie;  @synthesize title; // this seems to be issue - but I don't understand why? @synthesize rating; @synthesize year;  @end 

Can anybody explain where I've gone wrong?

回答1:

I assume you are using ARC.

Under ARC, the ownership qualification of the property must match the instance variable (ivar). So, for example, if you say that the property is "strong", then the ivar has to be strong as well.

In your case you are saying that the property is "assign", which is the same as unsafe_unretained. In other words, this property doesn't maintain any ownership of the NSString that you set. It just copies the NSString* pointer, and if the NSString goes away, it goes away and the pointer is no longer valid.

So if you do that, the ivar also has to be marked __unsafe_unretained to match (if you're expecting the compiler to @synthesize the property for you)

OR you can just omit the ivar declaration, and just let the compiler do that for you as well. Like this:

@interface Movie : NSObject  @property(assign) NSString *title; @property(assign) int rating; @property(assign) int year;  @end 

Hope that helps.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!