Klemen
Klemen

Reputation: 2180

Subclassing PFUser. Accessing current user

Im trying to subclass PFUser, because I want to add some properties, but I also need that [MyUserSubclass currentUser] return MyUserSubclass istead of PFUser instance.

My current code goes like this:

+ (instancetype)currentClient {
    MyUserSubclass *client = [MyUserSubclass objectWithoutDataWithObjectId:[PFUser currentUser].objectId];
    [client fetch];
    return client;
}

At method [client fetch] my app crashes and a console got a warning:Can't refresh an object that hasn't been saved to the server.

Please help.

Upvotes: 2

Views: 754

Answers (1)

knshn
knshn

Reputation: 3461

If you check PFUser.h in Parse library, you will see currentUser returns instancetype.

+ (instancetype)currentUser;

This means that if you subclass PFUser, then currentUser returns an object of the type of the subclass, which is MyUserSubclass in your case.

Here is a short example of subclassing PFUser:

User.h

#import <Parse/Parse.h>

@interface User : PFUser <PFSubclassing>

@property (nonatomic, strong) NSString *firstName;

+ (User *)user;
+ (BOOL)isLoggedIn;

@end

User.m

#import "User.h"
#import <Parse/PFObject+Subclass.h>

@implementation User

@dynamic firstName;

+ (User *)user {
    return (User *)[PFUser user];
}

+ (BOOL)isLoggedIn
{
    return [User currentUser] ? YES: NO;
}

@end

Notice that I need to implement a +(User *)user; method, because in PFUser.h it is +(PFUser *)user; rather than instancetype.

Upvotes: 2

Related Questions