访问另一个类的变量
如何访问其他类的变量?我就是这样实现的。
@interface Class1 :NSObject {
NSString *Data;
}
@property (nonatomic, retain) NSString *Data;
@implementation Class1
@synthesize Data;
someMethod{
self.Data = @"something";
}
and in Class2 :
@implementation Class2
someMethodOfClass2{
Class1 *c=[[Class1 alloc]init];
[c someMethod];
NSString *str=c.Data;
}
我在 Class2 中得到 c.Data 为 null。我在这里做错了什么吗?
-----------myClass1--------------
@interface APIManager : NSObject {
NSString *Data;
}
@property (nonatomic, retain) NSString *Data;
-(void)getData;
@end
@implementation APIManager
@synthesize Data;
-(void)getData{
self.Data=@"response";
}
--------myClass2--------------
@interface Search : NSObject {
}
-(void)searchForItems:(NSString *)query;
@end
@implementation Search
-(void)searchForItems:(NSString *)query {
APIManager *apiManager=[[APIManager alloc]init];
[apiManager getData];
NSLog(@"%@",[apiManager Data]);
}
How to access variables of other class? This is how I implemented it.
@interface Class1 :NSObject {
NSString *Data;
}
@property (nonatomic, retain) NSString *Data;
@implementation Class1
@synthesize Data;
someMethod{
self.Data = @"something";
}
and in Class2 :
@implementation Class2
someMethodOfClass2{
Class1 *c=[[Class1 alloc]init];
[c someMethod];
NSString *str=c.Data;
}
I get c.Data as null in Class2. Am I doing anything wrong here?
-----------myClass1--------------
@interface APIManager : NSObject {
NSString *Data;
}
@property (nonatomic, retain) NSString *Data;
-(void)getData;
@end
@implementation APIManager
@synthesize Data;
-(void)getData{
self.Data=@"response";
}
--------myClass2-------------
@interface Search : NSObject {
}
-(void)searchForItems:(NSString *)query;
@end
@implementation Search
-(void)searchForItems:(NSString *)query {
APIManager *apiManager=[[APIManager alloc]init];
[apiManager getData];
NSLog(@"%@",[apiManager Data]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能应该使用
self.Data = @"something"
而不是self.Data = "something"
You should probably use
self.Data = @"something"
instead ofself.Data = "something"
在 Objective-C 中,你必须使用
@"something"
而不是"something"
。另外你是不是缺少变量声明?在您的 @interface 中,您应该执行类似 NSString *Data 的操作。In Objective-C you have to use
@"something"
instead of"something"
. Also aren't you missing the variable declaration? In your@interface
you should do something likeNSString *Data
.