tags:

views:

44

answers:

1

Hello.

I have the following code:

In .h:

interface .... {
   int CatID;
   ... 
}
@property (readwrite) int CatID;

.m:
// Already includes the header file (.h) 
implementation ... {
   @synthesize CatID;
....
   - (void)setCatIDa:(int)cid {
       self.CatID = 20;

       NSLog(@"cat id: %d", CatID); // this returns 20
   }

   - (IBAction)someTest:(id)sender {
        NSLog(@"cat id: %d", CatID); // returns 0
   }

}

How come its returning 0?

Also the NIB views are changing between the set and get

A: 

Without the complete code I can't see exactly what would cause that behaviour, but I would point out a couple of things that could be improved and may have an impact.

  • The property definition doesn't include (assign) - it's likely defaulted, but i'd include it just in case. So @property (assign, readwrite) NSInteger catId;
  • The iVar's name starts with an upper case character - it's an instance, so lowercase should be used. @synthesize catId;
  • When referencing it, use self.catId

If you could post the completed interface and implementation it'd be easier to test. I've written something very similar here and it works fine...

dannywartnaby
assign is the default. His property declaration is OK. There's also nothing wrong with using int as the property type.
JeremyP
Thanks for clarifying the assign jeremy. Oh, and I didn't mean to suggest int *was* wrong - I simply wasn't paying that much attention to it when re-writing.
dannywartnaby
My money is on it needing to be `self.CatID` for access to work correctly. I also agree the property should start with lowercase, but I don't think it is the issue right now.
theMikeSwan
@theMike: In the class `CatID` works just fine, you just directly use the ivar instead of the generated setter/getter.
Georg Fritzsche
@George Then why have I had problems when trying to access a property directly from with in the class myself? Happens pretty much all the time.
theMikeSwan
@theMike: I can't know without seeing example code, but the synthesized accessors just use the instance variables themselves. There might be cases where you shadow the ivars with local variables, etc.
Georg Fritzsche