int variable is not getting assigned??

Discussion in 'iOS Programming' started by AbhishekApple, Aug 27, 2010.

  1. AbhishekApple macrumors member

    Joined:
    Aug 5, 2010
    #1
    i have declared int variable totRecint as global but it is not getting assigned with value
    (showing garbage memory location)????

    but the string variable totRecstr gets a value from the array

    Code:
    @implementation SearchViewController
    
    NSString *totRecstr;
    int totRecint;
    
    - (void)requestFinished:(ASIHTTPRequest *)request
    {
    NSArray *arryPage = [[request responseString] componentsSeparatedByString:@","];
    
    
    		totRecint = (int)[arryPage objectAtIndex:0];
    		
    		totRecstr = [arryPage objectAtIndex:0];
    }
    ......
    @end
     
  2. Cromulent macrumors 603

    Cromulent

    Joined:
    Oct 2, 2006
    Location:
    The Land of Hope and Glory
    #2
    What is the type of the object stored in the array at index 0? The cast to int looks suspicious.
     
  3. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #3
    You can't do that. ints are primitives, not objects and therefore cannot be stored inside an NSArray without a wrapper (ie: NSNumber). What you are doing here is setting totRecint to the value of the pointer at index 0. You need to convert the returned value to an int first before you can perform the assignment. Hint: look at the "Getting Numeric Values" section in the NSString documentation.

    Edit: Mixed up NSInteger and NSNumber, need more coffee. Thanks ranguvar
     
  4. ranguvar macrumors 6502

    Joined:
    Sep 18, 2009
    #4
    NSInteger is not an object. NSNumber is.
     
  5. fluxforge macrumors member

    Joined:
    Apr 16, 2010
    Location:
    europe
    #5
    ok.

    Code:
    [arryPage objectAtIndex:0];
    returns you a pointer to an NSObject. if you cast this pointer to int you will get the memory address the pointer points to written into the int variable. that's why you see "garbage" values in your int variable;

    do this instead:

    Code:
    totRecint = [[arryPage objectAtIndex:0] intValue];
    
     
  6. rrichar macrumors newbie

    Joined:
    Aug 13, 2010
    #6
    Assuming your variable is Counter:

    1.) in your .h file put the following

    int counter;

    2.) in the .m file put the following code in the viewdidload IBACTION

    in counter = 0;
     
  7. AbhishekApple thread starter macrumors member

    Joined:
    Aug 5, 2010
    #7
    Thanks to all for not only giving the answer but also explaining why?
     

Share This Page