Static attribute, Static Class, Singleton Pattern - objective-c

I have 3 class.
Class A contains :
A static variable "dataX".
A setter method to set the data.
A getter method to return the data value.
Class B
Class C.
the flow is as follows:
The Class B instanciates the Class A and initialize the variable "dataX" with the setter method.
Afterwards, the class C instantiates the Class A in the viewDidLoad method and gets the value of the static variable.
But even if the variable in Class A is static, the variable is always null.
I guess that I need to put the Singleton Pattern with a static Class A and not simply a static attribute.
What is the syntax to specify a Class as Static?
The code below:
// HandleMessage.h
#interface HandleMessage : NSObject
#property *NSString nameFile;
// Getter
- (NSString *)getNameFile;
// Setter
- (void)setNameFile: (NSString *) value;
#end
And:
// HandleMessage.m
#import "HandleMessage.h"
#implementation HandleMessage
static nameFile;
#synthesize nameFile ;
// Getter definition
- (NSString *)getNameFile{
return nameFile;
}
// Setter definition
- (void)setNameFile: (NSString *) value{
nameFile = value;
}

When you instantiate another instance of a class of course this instance's value is null.
You can work with singletons or store your data elsewhere (if you want to keep data between app starts in your user defaults using NSUserdefaults)

what do you mean by "Class as Static"??
you can use singleton pattern, which i described in this answer
or using class method
ClassA.h
#interface ClassA
+ (void)setData:(int)data;
+ (int)getData;
#end
ClassA.m
static int sData;
#implementation ClassA
+ (void)setData:(int)data {
sData = data;
}
+ (int)getData {
return data;
}
#end

Related

Using ObjC class extensions' vars in class category

I declare a class extension interface adding vars to it. Is it possible to access those vars in a category of that class?
Sure - any variable is accessible through the runtime, even if it isn't visible in the #interface:
SomeClass.h
#interface SomeClass : NSObject {
int integerIvar;
}
// methods
#end
SomeClass.m
#interface SomeClass() {
id idVar;
}
#end
#implementation SomeClass
// methods
#end
SomeClass+Category.m
#implementation SomeClass(Category)
-(void) doSomething {
// notice that we use KVC here, instead of trying to get the ivar ourselves.
// This has the advantage of auto-boxing the result, at the cost of some performance.
// If you'd like to be able to use regex for the query, you should check out this answer:
// http://stackoverflow.com/a/12047015/427309
static NSString *varName = #"idVar"; // change this to the name of the variable you need
id theIvar = [self valueForKey:varName];
// if you want to set the ivar, then do this:
[self setValue:theIvar forKey:varName];
}
#end
You can also use KVC to get iVars of classes in UIKit or similar, while being easier to use than pure runtime-hacking.

Member variable declared in .m file keeps its value between instances of the class

I have the follow implementation file for MyClass:
BOOL myBool;
#implementation MyClass
// ...
- (void) someMethod {
myBool = YES;
}
#end
It seems like myBool will be YES for every instance of MyClass after someMethod is called on just one instance of MyClass. However if I define myBool like this it has a unique value for each instance of MyClass:
#interface MyClass ()
#property (nonatomic) BOOL myBool;
#end
What is the difference between the above two "member variable" syntaxes?
The difference is that in 1st case it is not member variable, it is global variable so it naturally persists its value between multiple instances of your class.
If you want to declare ivar in class implementation file you can do the following:
#implementation MyClass{
BOOL myBool;
}
...

Issue understanding "Referring to Instance Variables" from Apple guide

I am trying to understand Referring to Instance Variables from Apple guide but having issue understudying this, Apple Doc says
...When the instance variable belongs to an object that’s not the receiver, the object’s type must be made explicit to the compiler through static typing. In referring to the instance variable of a statically typed object, the structure pointer operator (->) is used.
Suppose, for example, that the Sibling class declares a statically typed object, twin, as an instance variable:
#interface Sibling : NSObject
{
Sibling *twin;
int gender;
struct features *appearance;
}
As long as the instance variables of the statically typed object are within the scope of the class (as they are here because twin is typed to the same class), a Sibling method can set them directly:
- makeIdenticalTwin
{
if ( !twin )
{
twin = [[Sibling alloc] init];
twin->gender = gender;
twin->appearance = appearance;
}
return twin;
}
Referring to instance variable means, accessing the class instance vars
For example:
#interface ClassA : NSObject
{
int value;
}
- (void) setValue:(int) val;
#implementation ClassA
- (void) setValue:(int) val
{
//here you could access class a value variable like this
value = val;
}
Now accessing other classes variables
take for example this class
#interface ClassB : ClassA
{
ClassA aClass;
}
- (void) setValueInAClass:(int) val;
#implementation ClassB
- (void) setValueInAClass:(int) val
{
//class b could access variables from class a like this
aClass->value = val;
}
Please note that this is very un recommended to do, using the "->" breaks the encapsulation of class a, so dont in 99% of the cases referring to class variables using the "->" is a mistake

#property and setters and getters

If I create a #property and synthesize it, and create a getter and setter as well like so:
#import <UIKit/UIKit.h>
{
NSString * property;
}
#property NSString * property;
--------------------------------
#implementation
#synthesize property = _property
-(void)setProperty(NSString *) property
{
_property = property;
}
-(NSString *)property
{
return _property = #"something";
}
Am I correct in assuming that this call
-(NSString *)returnValue
{
return self.property; // I know that this automatically calls the built in getter function that comes with synthesizing a property, but am I correct in assuming that I have overridden the getter with my getter? Or must I explicitly call my self-defined getter?
}
is the same as this call?
-(NSString *)returnValue
{
return property; // does this call the getter function or the instance variable?
}
is the same as this call?
-(NSString *)returnValue
{
return _property; // is this the same as the first example above?
}
There are a number of problems with your code, not least of which is that you've inadvertently defined two different instance variables: property and _property.
Objective-C property syntax is merely shorthand for plain old methods and instance variables. You should start by implementing your example without properties: just use regular instance variables and methods:
#interface MyClass {
NSString* _myProperty;
}
- (NSString*)myProperty;
- (void)setMyProperty:(NSString*)value;
- (NSString*)someOtherMethod;
#end
#implementation MyClass
- (NSString*)myProperty {
return [_myProperty stringByAppendingString:#" Tricky."];
}
- (void)setMyProperty:(NSString*)value {
_myProperty = value; // Assuming ARC is enabled.
}
- (NSString*)someOtherMethod {
return [self myProperty];
}
#end
To convert this code to use properties, you merely replace the myProperty method declarations with a property declaration.
#interface MyClass {
NSString* _myProperty;
}
#property (nonatomic, retain) NSString* myProperty
- (NSString*)someOtherMethod;
#end
...
The implementation remains the same, and works the same.
You have the option of synthesizing your property in your implementation, and this allows you to remove the _myProperty instance variable declaration, and the generic property setter:
#interface MyClass
#property (nonatomic, retain) NSString* myProperty;
- (NSString*)someOtherMethod;
#end
#implementation MyClass
#synthesize myProperty = _myProperty; // setter and ivar are created automatically
- (NSString*)myProperty {
return [_myProperty stringByAppendingString:#" Tricky."];
}
- (NSString*)someOtherMethod {
return [self myProperty];
}
Each of these examples are identical in how they operate, the property syntax merely shorthand that allows you to write less actual code.
return self.property – will call your overridden getter.
return _property; – accesses the property's instance variable directly, no call to the getter.
return property; – instance variable.
EDIT: I should emphasize that you will have two different NSString variables -- property and _property. I'm assuming you're testing the boundaries here and not providing actual production code.
above answer elaborate almost all the thing , i want to elaborate it little more.
// older way
#interface MyClass {
NSString* _myProperty; // instance variable
}
- (NSString*)myProperty; // getter method
- (void)setMyProperty:(NSString*)value;//setter method
#end
the instance variable can not be seen outside this class , for that we have to make getter and setter for it.
and latter on synthesis it in .m file
but now
we only used
#property(nonatomic) NSString *myProperty;
the #property is an Objective-C directive which declares the property
-> The "`nonatomic`" in the parenthesis specifies that the property is non-atomic in nature.
-> and then we define the type and name of our property.
-> prototyping of getter and setter method
now go to .m file
previously we have synthesis this property by using #synthesis , now it also not required it automatically done by IDE.
little addition : this `#synthesis` now generate the getter and setter(if not readonly) methods.

Objective-C : How may I hide a class member from outside the class?

I'm fighting with something and I don't find any satisfying solution.
I have a class with a "myMutableArray" member.
I would like the class to manage itself adding and removing items from the array, so I don't want any other class being able to access the member and call NSMutableArray methods on it.
In an ideal situation, I would like to have a private getter (to be able to call self.myMutableArray) and a public setter for this member.
Do you know how I may achieve this ?
In other words :
I would like other classes
be able to call
- [oneInstance setMyMutableArray:thisArray]; // set
- oneInstance.myMutableArray = thisArray; // set using setter
- thisArray = oneInstance.myMutableArray; // get
- [oneInstance addItem:anItem]; // add
not being able to call :
- [oneInstance.myMutableArray add:etc...] // add
I would like my class
be able to call
- self.myMytableArray = [NSMutableArray array]; // set
- thisArray = self.myMytableArray ; // get
Thank you.
Is there any reason you need the public setter? It sounds like the class itself owns the array. You'd probably be better off not providing any public property access to the field, and making a public method which copies the values into your private field.
// public interface, in the .h file
#interface MyClass : // superclass, protocols, etc.
- (void) setSomething:(NSArray *)values;
#end
// private interface, not in the .h
#interface MyClass ()
#property (/* attributes */) NSMutableArray *myMutableArray;
#end
#implementation MyClass
#synthesize myMutableArray = myMutableArray_;
- (void) setSomething:(NSArray *)values
{
[self.myMutableArray setArray:values];
}
#end
Foo.h
#interface Foo : NSObject
#property(readonly, retain) NSArray * myReadonlyArray;
- (void) addItem: (Item *) anItem;
- (BOOL) publiclyDoSomething;
#end
Foo.m
#interface Foo()
#property(readwrite, retain) NSMutableArray * myMutableArray;
- (void) doSomethingInPrivate;
#end
#implementation Foo
#synthesize myMutableArray = myMutableArray_;
- (void) addItem: (Item *) anItem
{
// assuming myMutableArray_ was already iniitialized
[self.myMutableArray addObject: anItem];
}
- (NSArray *)myReadonlyArray
{
return self.myMutableArray;
}
... rest of methods (including the public/private) implementations ...
#end
Some details:
Objective-C has "instance variables", not "member variables".
The above defines a public getter and private setter that is synthesized automatically. For clarity's sake, I also added a public method and a private method.
"Public" and "private" in Objective-C are defined entirely by visibility to the compiler. The setter for myMutableArray and the method doSomethingInPrivate are only private because their declarations in an #interface cannot be imported.
self.myMutableArray and [self myMutableArray] do the same thing; the . syntax is merely short hand for an equivalent method call (with a few edge case details beyond this question)
#property in the #interface is purely short hand for method declarations (with a bit of extra metadata).
#interface Foo() is a class extension and not a category. It exists for exactly the purpose demonstrated above; to extend the #interface of a class with additional declarative information whose scope should be limited. It can appear in a header file that, say, you only import in your library's implementation to create library-private functionality.
#dynamic is used when you neither #synthesize an #property nor provide a conventional method implementation. It is not needed otherwise!
I'm probably forgetting something.