Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-(bool) not returning

I am really new to Xcode and iPhone development. I have written a function in my appDelegate.m file called getISlogged;. It goes something like this:

- (BOOL) getISlogged {
    NSUserDefaults *usenow = [NSUserDefaults standardUserDefaults];
    NSNumber *islog = nil;
    if(usenow){
        islog = [usenow objectForKey:@"is_log"]; // should equal 1 or 0...
    }

    UIAlertView * alert1 = [[UIAlertView alloc] initWithTitle:@"works" message:@"test1" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];
    [alert1 show];
    if (islog == [NSNumber numberWithInt:(1)]) {
       return YES;
    } else {
        return NO;
    }
}

Ok, now i call it from my viewController.m like so:

SWGAppDelegate *appDelegate = (SWGAppDelegate *)[[UIApplication sharedApplication]delegate];
NSString *islog = @"no";
if(appDelegate.getISlogged){
   islog=@"yes";
}

Now when I run it I always get Thread 1: breakpoint 2.1 and i have no idea what do do with that. I have tried removing all the code and leaving just return YES; in the function and I still get the same error =\

Any help or tips would help thank you.

like image 981
Dvir Levy Avatar asked Nov 21 '25 17:11

Dvir Levy


1 Answers

Just simply return the boolValue of the NSNumber instance, rather than extracting its integer value, comparing it to 1, and returning YES or NO based on that, e.g. your entire method could be reduced to:

- (BOOL) getISlogged {
    return [[[NSUserDefaults standardUserDefaults] objectForKey:@"is_log"] boolValue];
}

If the key does not exist in the user defaults, the result of this method will be NO.

Another “code-smell” is that you are assigning Boolean values to a string (with @"yes" and @"no" being assigned to islog). There is nothing wrong with that if you simply plan to write the string somewhere, e.g. to a log, but if you are planning on using this variable to determine whether or not to write to a log, then you should instead make it a BOOL. Strings are for storing text, that's it.

Lastly, remember that in Objective-C the == operator compares object identity (that is, it confirms that two references point to the same object), it doesn't compare object equality. You can use the built-in isEqual: methods for NSNumber or “extract” the boxed value and compare against another unboxed value, e.g. either of this will do the trick:

if ([islog isEqualToNumber:[NSNumber numberWithInt:1]])
    // do something

// or

if ([islog intValue] == 1)
    // do something
like image 52
dreamlax Avatar answered Nov 23 '25 06:11

dreamlax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!