Ios 在类方法中设置属性变量
目前,我知道我不能在类方法中设置属性变量 例如:Ios 在类方法中设置属性变量,ios,objective-c,properties,parse-platform,class-method,Ios,Objective C,Properties,Parse Platform,Class Method,目前,我知道我不能在类方法中设置属性变量 例如: #ISUser.h @interface ISUser : NSObject @property (nonatomic, retain) NSString *username; @property (nonatomic, retain) NSString *password; @property (nonatomic, retain) NSString *email; @property (nonatomic, retain) NSString
#ISUser.h
@interface ISUser : NSObject
@property (nonatomic, retain) NSString *username;
@property (nonatomic, retain) NSString *password;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *firstname;
@property (nonatomic, retain) NSString *lastname;
+ (void)logInWithUsernameInBackground:(NSString *)username
password:(NSString *)password
block:(ISUserResultBlock)block;
@end
我正在浏览Parse的框架,并试图更好地理解如何像他们那样实现登录。class方法(void)logInWithUsernameInBackground:password:block
是我尝试分配属性变量username和password的地方,但这是不可能的
以下是当前方法的实现:
+ (void)logInWithUsernameInBackground:(NSString *)username password:(NSString *)password block:(ISUserResultBlock)block
{
//self.username = username // Of course, I cannot do this
NSString *preferredLanguageCodes = [[NSLocale preferredLanguages] componentsJoinedByString:@", "];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kAPIHost, kAPIPath]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"%@, en-us;q=0.8", preferredLanguageCodes] forHTTPHeaderField:@"Accept-Language"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSData * data = [[NSString stringWithFormat: @"command=login&username=%@&password=%@", username, password] dataUsingEncoding: NSUTF8StringEncoding];
[request setHTTPBody:data];
ConnectionBlock *connection = [[ConnectionBlock alloc] initWithRequest:request];
[connection executeRequestOnSuccess: ^(NSHTTPURLResponse *response, NSString *bodyString, NSError *error) {
block([self user], error);
} failure:^(NSHTTPURLResponse *response, NSString *bodyString, NSError *error) {
block([self user], error);
}];
}
在parse PFUser.h文件中,这是一个类方法。。。但是他们如何分配属性变量呢
我知道静态变量可以在一个类方法中赋值/设置,但我想从另一个类访问这些变量
编辑:在查看第一条注释后,ISUser类已经实现了一个单例
+ (instancetype)currentUser
{
static ISUser *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
但是现在呢?我需要重写init方法并设置变量?但是init方法如何知道将变量设置为什么呢?我是否必须向
+(instancetype)currentUser
添加参数,比如+(instancetype)currentUser:username password:(NSString*)password
,然后也重写init方法+(instancetype)currentUser
是我从PFUser框架中提取的另一个类方法 不能在类方法中设置属性。您可以在实例方法上执行此操作。这是因为属性用于类的实例
在parse login方法中,它们使用一些属性作为方法参数,并将它们用于登录过程,但不操纵它们
希望对您有所帮助您可以使用带有单例模式的类方法-第一次调用
logInWithUsernameInBackground
将分配一个对象并执行登录。后续调用将使用现有对象,并直接调用完成块-