Ios 在多个类中访问属性时遇到问题
嗯。我假设我对ARC的误解是我发布这篇文章的原因,但它就在这里。所以我有一个类,让我们称之为classa,我调用它并引用它,它在classB中以我所希望的方式完美地工作。现在,当我访问类C内部的类A时,我需要的属性返回空值。注意:由于我的方法的结构,每次调用时我只需要访问属性,而不需要调用方法,因为每次调用时方法返回的结果不同。我做错了什么?下面是我如何在类A中声明头文件中的属性: h 下面是我设置它的方法:Ios 在多个类中访问属性时遇到问题,ios,objective-c,Ios,Objective C,嗯。我假设我对ARC的误解是我发布这篇文章的原因,但它就在这里。所以我有一个类,让我们称之为classa,我调用它并引用它,它在classB中以我所希望的方式完美地工作。现在,当我访问类C内部的类A时,我需要的属性返回空值。注意:由于我的方法的结构,每次调用时我只需要访问属性,而不需要调用方法,因为每次调用时方法返回的结果不同。我做错了什么?下面是我如何在类A中声明头文件中的属性: h 下面是我设置它的方法: -(NSString *)grabUserKey{ //Grabs a str
-(NSString *)grabUserKey{
//Grabs a string from a web service each time it is called
NSString *getUserKey = [NSString stringWithFormat:@"%@/webservices/***/mobile_services_ios7.cfc?method=create_account&client_key=%@", [self grabHomeURl],CLIENT_KEY];
NSLog(@"%@", getUserKey);
NSString * user_key = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:getUserKey] encoding:NSUTF8StringEncoding error:nil];
//I only need this property once and only once. However, this property is null the second time I call it
self.userKey = user_key;
return user_key;
}
现在,当我尝试在另一个方法中使用此属性时,在同一个类(emphasis.)中,我在第二次引用它时得到一个空结果:
-(NSString *) returnFilePath{
NSString *userDBPath = [PATH stringByAppendingPathComponent:CLIENT_KEY];
//self.userKey returns null when called in class C, but not in class A
NSString * userFilePath = [userDBPath stringByAppendingPathComponent:self.userKey];
return userFilePath;
}
下面是如何初始化类C:
h
m
那么,为什么当我在类B中访问类A(在编译时第一次访问类A)时,它可以工作呢。但是当我访问C类中的A类时,我得到了空的userKey?希望我能给大家解释清楚。您在class a的属性
NSString*userKey
中设置了一个用户密钥。它不是一个持久性数据。您必须将数据保存到其他地方,如NSUserDefault
根据你附加的代码
_filePath = [[RetriveFilePath alloc]init];
NSString * localShow = [_filePath returnFilePath];
您实例化了retrievefilepath
并试图获取userKey;但是,RetrieveFilePath中没有用户密钥,因为您还没有获得数据
无论您在哪里调用[\u filePath grabUserKey]
,它都不是与\u filePath相同的实例
使用NSUserDefault或将类设置为singleton。您确定在API调用完成后已将用户密钥从类C请求到类A吗?此外,为什么您使用
retain
而不是strong
?在调用returnFilePath
之前,您是否在C类中调用了grabUserKey
?@trick14第二点很好。只是把它切换到了strong,仍然是c类中相同的空结果。没有真正理解你的第一点。你的意思是:[[u filepath userkey]吗?你的第二个评论是我的处境有点棘手。我只能调用grabUserKey方法一次,而且只能调用一次。每次调用grabUserKey,我都会得到不同的结果,这是我无法得到的。希望这是有意义的。@trick14我意识到这可能会令人困惑,因为我的实例方法“grabUserKey”返回一个字符串。从技术上讲,它应该只是一个设置属性“self.userKey”的void方法(如果有意义的话)。类a是retrievefilepath
。我说得对吗?
@property (retain) RetriveFilePath * filePath;
_filePath = [[RetriveFilePath alloc]init];
NSString * localShow = [_filePath returnFilePath];
_filePath = [[RetriveFilePath alloc]init];
NSString * localShow = [_filePath returnFilePath];