我在Objective-C中有一些代码。我想我收到了NSString类型,但是当我尝试将其保存在Core Data中时,出现了user.clientID = clientID;错误,例如:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "clientID"; desired type = NSString; given type = __NSCFNumber; value = 29.'

所以,这是我的代码:

我的数据管理器单例 PKDataManager.h
+(PKDataManager*) sharedManager;

- (void)updateCoreDataUserWithID:(NSString*) userID
                 andClientID:(NSString*) clientID;

PKDataManager.m
- (void)updateCoreDataUserWithID:(NSString*) userID
                 andClientID:(NSString*) clientID{

       PKUser*user = [NSEntityDescription
       insertNewObjectForEntityForName:@"PKUser"
       inManagedObjectContext:self.managedObjectContext];
       user.userID = userID;
       user.clientID = clientID; ///// error showing here
       [self.managedObjectContext insertObject:user];
       [self.managedObjectContext save:nil];
}

我对API的单例 PKServerManager.h
+ (PKServerManager*) sharedManager;

- (void) sendUserID:(NSString*) userID
              onSuccess:(void(^)(NSString* clientID)) success
              onFailure:(void(^)(NSError* error, NSInteger statusCode)) failure;

PKServerManager.m
- (void) sendUserID:(NSString*) userID
                  onSuccess:(void(^)(NSString* clientID)) success
                  onFailure:(void(^)(NSError* error, NSInteger statusCode)) failure{
        NSDictionary* params =
        [NSDictionary dictionaryWithObjectsAndKeys:
         userID, @"userID", nil];
        [self.requestOperationManager
         POST:@"app/registration"
         parameters:params
         progress:nil
         success:^(NSURLSessionTask *task, NSDictionary* responseObject) {
            NSLog(@"JSON: %@", responseObject);
            NSString* clientID = (NSString*)[responseObject objectForKey:@"clientId"];
            if (success) {
                success(clientID);
            }
         } failure:^(NSURLSessionTask *operation, NSError *error) {
         }];
}

和我的代码:
PKProfile.m
[[PKServerManager sharedManager]
     sendUserID:profile.userID
     onSuccess:^(NSString* clientID) {
         NSLog(@"clientID %@", clientID);
         [[PKDataManager sharedManager] updateCoreDataUserWithID: profile.userID
                                                     andClientID: clientID];
     }
     onFailure:^(NSError *error, NSInteger statusCode) {
     }];

最佳答案

您的错误是告诉您响应中包含客户端ID的数字值(并在responseObject中表示为NSNumberNSCFNumber是更广泛的NSNumber类集群的一部分)。您的JSON响应似乎包含以下内容:

{
    ...,
    "clientId": 42
}

而不是
{
    ...,
    "clientId": "42"
}

与其专注于如何将NSNumber转换为NSString,不如我倾向于考虑将整个应用程序中的客户端ID更改为NSInteger(或NSNumber)。如果这些ID确实是数字值,则最好具有能反映该值的类型。

关于ios - objective-c 。 NSString更改为NSCFNumber,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48668615/

10-10 08:46