-1

I’m a newer in Objective C. I found can access the private variable outside. I just get a warning Like follows:

@interface foo : NSObject
{
   @private 
        int b;
}
-(id) init;
@end
//omit the implement
int main()
{
    foo *a = [[foo alloc] init];
    printf("%d", a->b);
}

So dose the private keyword only work on its subclass? If Yes, why need protected keyword

Samuel
  • 5,977
  • 14
  • 55
  • 77
  • it should be 'a->b' in your code – La bla bla Sep 21 '12 at 03:11
  • 1
    First of all, you don't just get a warning, you get an error on the modern compiler (you got a warning with gcc years ago). Also, the code above wouldn't have even compiled in gcc because you've create your own root class, which has no alloc method. Finally, you're trying to access an instance variable on the class itself (which also would have caused an error, even under gcc). – Jason Coco Sep 21 '12 at 03:12
  • I'm sorry. I was supposed to write a->b – Samuel Sep 21 '12 at 03:22

1 Answers1

0

The code you provided accesses ab, not b. Furthermore, you're using the class name foo, but you appear to be trying to access an instance variable named ab. If you want to access an instance variable, you'll first need to create an instance of the class:

foo f = [foo new];

The @private keyword prevents you from accessing b from anywhere other than the methods defined by class foo.

Update:

I'm assure the codes is correct now. So why I can access the variable outside.

If you're compiling with an Objective-C compiler, you normally can't:

Private variable error image

If you're able to get the code to compile and access b, there's something odd going on. What compiler are you using, and what settings?

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • I'm really sorry. I made a mistake on writing. Please read it again. – Samuel Sep 21 '12 at 03:05
  • As a matter of general Objective-C syntax, it is generally a good idea to avoid use of `new`: cf. http://stackoverflow.com/questions/719877/use-of-alloc-init-instead-of-new-objective-c – Alex Reynolds Sep 21 '12 at 03:14
  • @AlexReynolds In fact, I always use alloc/init myself, but new seems to better make my point here that you need to create a new instance of foo. I don't agree that one should *avoid* new -- it's in most respects the same thing and basically comes down to a matter of style. Probably the best reason to prefer alloc/init is that it's just more common these days. – Caleb Sep 21 '12 at 04:24
  • Hi I'm sorry for my carelessness. I'm assure the codes is correct now. So why I can access the variable outside . – Samuel Sep 21 '12 at 05:05