ios7 - How to get and set private instance variable/ property from outside a class Objective C? -
i have class myconfig property/ variable nsstring * url
. private, don't want able set url outside of myconfig class. example, don't want following allowed:
myconfig * myconfig = [[myconfig alloc] init]; myconfig.url = @"some url";// want forbid
my goals:
- forbit setting of variable/ property via dot notation
- use automatically generated/ standard getter (
myconfig.url
) , setter ([myconfig seturl]
) - don't want write getters , setters myself
what have: myconfig.h
@interface myconfig : nsobject @property (readonly) nsstring * url; @end
problem: standard getter not working!
myconfig * myconfig = [[myconfig alloc] init]; [myconfig seturl];// instance method "-seturl:" not found (return default type "id")
this shouldn't case according this right?
is there better way achieve goal?
you try creating public property getter such have , create private version in implementation file such below.
myconfig.h
// public interface world can see @interface myconfig : nsobject @property (readonly) nsstring *url; // readonly getter generated not setter @end
myconfig.m
#import "myconfig.h" // private interface implementation can see @interface myconfig() // class extension @property (nonatomic, strong) nsstring *url; // private getter , setter @end @implentation myconfig // rest of code... @end
the way have implemented using class extensions, syntax declare class extension same 1 creating category empty name. , quite important part don't have define implementation block, implementation extension , code in has implemented in main implementation block.
using class extension method (not possible categories) can have property readonly
access public facing , readwrite
access privately. declare property readonly
in header file , redeclare readwrite
in class extension.
Comments
Post a Comment