Frage

I have the following code for retriving an integer from Preferences. I have made a class for doing the same. the code is as below

PreferenceHelper.h

#import <Foundation/Foundation.h>

@interface PreferenceHelper : NSObject
+ (id) sharedHelper;
- (int) getInt:(NSString *)key;
@end

PreferenceHelper.m

#import "PreferenceHelper.h"

@implementation PreferenceHelper
+ (id)sharedHelper {
    static PreferenceHelper *sharedMyHelper = nil;
    @synchronized(self) {
        if (sharedMyHelper == nil)
            sharedMyHelper = [[self alloc] init];
    }
    return sharedMyHelper;
}
- (int) getInt:(NSString *)key{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSInteger value = 0;
    if ([prefs valueForKey:key] == nil||key==nil) {
        value = 0;
        return 0;
    }
    else{
        value = [prefs integerForKey:key];
    }
    return (int)value;
}

Now I am trying to call the getInt inside a callback block in objective c as shown below

-(void)getFacebookDetails{
    __block int parseScore = 0;
    [FBRequestConnection startWithGraphPath:@"me/scores"
                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              if (!error){
                                  parseScore = [[PreferenceHelper sharedHelper] getInt:@"highscore"];
                                  NSLog(@"%d",parseScore);
                              } else {
                                  NSLog(@"failed");
                              }
                          }];
}

when I go inside the getInt using debugger the passed key value @"highscore" loses its value and as a result the parseScore returned is some garbage int value. Anyone knows the reason?

War es hilfreich?

Lösung

Define a block

 typedef void (^onListLoadCompleted)(NSString *strScore);

Method Call

[self getFacebookDetails:^(NSString *strScore) {
    NSLog(@"%@",strScore);
}];

Block Function

    -(void)getFacebookDetails:(onListLoadCompleted)block{

    __block int parseScore = 0;
    [FBRequestConnection startWithGraphPath:@"me/scores"
                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              if (!error){
                                  parseScore = [[PreferenceHelper sharedHelper] getInt:@"highscore"];
                                  NSLog(@"%d",parseScore);
                                  block(parseScore);
                              } else {
                                  NSLog(@"failed");
                                  block(@"failed");

                              }
                          }];

}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top