is there a way to define a variable thats accessible to some classes and not others? - iphone

In objective-c, the access to variables is limited to three types which is #public , #private , #protected (default) and #package .. these access modifiers allow us to access the variable through 4 situations in order :
1- access the variable from anywhere.
2- access the variable only inside the class.
3- access the variable from anywhere in the class and its subclasses.
4- access the variable from anywhere in the framework.
my question is: is there a way to define a variable which is accessible to some classes and not others ? (i.e. customised scope for variables)

What you're asking for is C++'s friend keyword. Friend classes in Objective-C discusses the topic.

You can use class extensions to create more flexible access control:
// MyClass.h
#interface MyClass : SomeSuperclass {
int ivar;
}
#end
// MyClass-Custom.h
#include "MyClass.h"
#interface MyClass () {
int anotherIvar;
}
#end
Now anotherIvar will be accessible only to code that #includes MyClass-Custom.h. You can create more class extensions on the same class to get additional access groups.

You would have to write your own setter and getter methods.
- (id) get_abc_value:(id)from {
if ([from isKindOfClass:[SomeRespectedClass class]]) {
return abc;
}
return nil;
}

Related

How to create global protocol method in iPhone?

I create one protocol method and I want to implement the protocol method in multiple classes
#protocol XMLProtocol <NSObject>
- (BOOL) hasAllRequiredAttributes :(NSDictionary*)attributeMap;
#end
I have use this following class methods
#import "XMLProtocol.h"
#interface MachineA : NSObject<XMLProtocol>
and its implementation method I will implement the protocol method
- (BOOL) hasAllRequiredAttributes:(NSDictionary *)attributeMap {
return false;
}
and also i use this protocol method in another class
#import "XMLProtocol.h"
#interface MachineB : NSObject<XMLProtocol>
and its implementation method I will implement the protocol method
- (BOOL) hasAllRequiredAttributes:(NSDictionary *)attributeMap {
return false;
}
my thought is where should I call the protocol method. I totally confused. How can i do this.
One way you can define a global implementation for your protocol method (if I understand correctly what you are asking) is defining a category on NSObject:
#implementation NSObject (XMLProtocol)
- (BOOL) hasAllRequiredAttributes:(NSDictionary *)attributeMap {
return false;
}
By doing like this every object will have that method. Don't know if this is sensible, but it's a way.
Another way would be defining a Machine base class from which both MachineA and MachineB derive; the protocol method would be defined in the base class:
#interface Machine : NSObject <XMLProtocol>
...
#implementation Machine
- (BOOL) hasAllRequiredAttributes:(NSDictionary *)attributeMap {
return false;
}
....
#end
#interface MachineA : Machine
...
and any derived class could redefine it, if required.
This is not as "global" as the NSObject category, but it might be a better solution if you can define a base class for all the classes that need implement that protocol.
You must write the implementation of the method in both classes, even if the implementations are identical.
In you particular situation notification would be great help full to you. Notification works same like protocol except it broadcast the message. so you could receive that call on multiple classes.
if you want to done with protocol than also it is very easy. just make sure you current view controller is referenced with delegate (i.e. obj.delegate = self). you can implement that on -viewWillAppear. so your current view controller only get called of that method. Delegate will only call one method at one place in a time.
IMHO a global protocol is not very good design for something as specific as XML parsing.
A #protocol doesn't have any implementation part by itself. It is just an API definition, think of it like a contract. Any class that conforms to a protocol must implement its mandatory methods and properties (there is a #optional clause).
For instance, you may have two implementations of an XML parser, one that works in iOS 4 and another one that works in iOS 5+. Both declared as conforming to XMLProtocol protocol. And both implementing - (BOOL) hasAllRequiredAttributes :(NSDictionary*)attributeMap;, let's imagine that they need to implement it differently.
Thanks to being compliant to XMLProtocol you don't care about the implementation details. You know that you'll pass an attribute map and you'll obtain a boolean indicating if it has all required attributes.
You call the method where ever you use those classes:
id <XMLProcotol> parser;
if (iOS4) {
parser = [[OldXMLParser alloc] initWithString:<#...#>];
} else {
parser = [[NewXMLParser alloc] initWithString:<#...#>];
}
/* you call the method without caring which parser class
* has been actually created thanks to the protocol
*/
if ([parser hasAllRequiredAttributes:theMap]) {
...
}
If the implementation of the methods are identical, you can make both a subclass of a common parent class that implements the common methods, present or not in the protocol.

Calling a method with return type "void" in same file

I've got a simple question.
In Objective-C, when you have a method you want to call, with a return type of void, how you you call it from another method?
The way I've been doing it in my application is this:
[self nameOfMethod];
But that causes Xcode to spit out the following error:
Method '-nameOfMethod' not found (return type defaults to 'id')
Though it seems to still be executing.
Am I calling it right, or is there a better way?
Thanks!
I’m guessing you haven’t declared -nameOfMethod in the class interface and you’re calling it from another method whose implementation precedes the implementation of -nameOfMethod, i.e.:
- (void)someMethod {
[self nameOfMethod];
}
- (void)nameOfMethod {
// …
}
When the compiler is parsing -someMethod and -nameOfMethod hasn’t been declared in the class interface, it generates a warning because it doesn’t know about -nameOfMethod yet.
There are essentially two solutions for this. You could reorder the implementation file so that -nameOfMethod appears before -someMethod, but that’s not always possible. A better solution is to declare -nameOfMethod in the class interface. If -nameOfMethod is supposed to be called by clients of your class, place it in the corresponding header file. On the other hand, if -nameOfMethod is only supposed to be called inside your implementation file, use a class extension. Supposing your class is named SomeClass, this is what your header and implementation files would look like:
// SomeClass.h
#interface SomeClass : NSObject {
// … instance variables
}
// … external methods
- (void)someMethod;
#end
// SomeClass.m
#import "SomeClass.h"
#interface SomeClass () // this is a class extension
// … internal methods
- (void)nameOfMethod;
#end
#implementation SomeClass
- (void)someMethod {
[self nameOfMethod];
}
- (void)nameOfMethod {
// …
}
#end
Using class extensions, the order of method implementations won’t matter.
You need to make sure that your interface file contains a definition for nameOfMethod - so;
-(void) nameOfMethod;
You're calling it correctly, but make sure that the interface for your (void) method is in your .h file.

How to use accessors within the same class in Objective C?

I have a few properties defined in my header file like so
#property (assign) bool connectivity_N;
#property (assign) bool isConnected_N;
In my implementation file I have an init and the synthesized properties like so
#implementation Map
#synthesize connectivity_N;
#synthesize isConnected_N;
a init to set the initial values like so
-(id) init
{
if( (self=[super init]) )
{
//initialise default properties
self.connectivity_N=NO;
self.isConnected_N=NO;
}
return self;
}
I'm running into an error that states Error: accessing unknown 'connectivity_N' class method. In this public method within the class
+(bool) isConnectable:(directions) theDirection{
bool isTheDirectionConnectable= NO;
switch (theDirection) {
case north:
isTheDirectionConnectable= self.connectivity_N;
break;
I'm not sure why is this so as I'm trying to grab the value of the property. According to the apple developer documentation "The default names for the getter and setter methods associated with a property are propertyName and setPropertyName: respectively—for example, given a property “foo”, the accessors would be foo and setFoo:"
That has given me a clue that I've done something wrong here, I'm fairly new to objective C so would appreciate anyone who spends the time to explain this to me.
Thanks!
You've defined isConnectable: as a class method by prefixing it with +. Probably you want it to be an instance method -- start it with a minus sign - instead.
You can't access self within class methods, because there is no object instance.
Although self exists in class methods, it doesn't refer to an object instance -- there is no object -- so you can't access object properties. (Thanks to Dave DeLong for the correction.)

iPhone static libraries: How to hide instance variable

I'm creating a static library to share using the following guide:
http://www.amateurinmotion.com/articles/2009/02/08/creating-a-static-library-for-iphone.html
In one of the functions, I return a "SomeUIView" which is a subclass of UIView and is defined in the public header, however I don't want to expose the internal instance variable of SomeUIView in the public header.
I've tried using categories for a private internal header file for SomeUIView, but I keep running into "Duplicate interface declaration for class 'SomeUIView'".
Does anyone know how to do this?
Thanks!
Categories and extensions can't add instance variables to a class. I'd go for the PIMPL idiom here - use a private implementation object:
// header
#class MyObjImpl;
#interface MyObj {
MyObjImpl* impl;
}
#end
// implementation file:
#interface MyObjImpl {
id someIvar;
}
// ...
#end
// ... etc.
This also keeps your public interface stable in case you want to add something for internal use.
The "duplicate interface" comes from missing parentheses in the second interface declaration:
// header:
#interface MyObj
// ...
#end
// implementation file:
#interface MyObj () // note the parentheses which make it a class extension
// ...
#end
You may also use the Objective-C 2 feature known as "Associative reference".
This is not really object-oriented API, but you can add/remove object to another object by using some simple functions of the runtime:
void objc_setAssociatedObject(id object, void * key, id value)
Sets the value or remove it when value is nil.
id objc_getAssociatedObject(id object, void * key)
Retrieve the value for specified key.
Note that this is also a mean to add "instance variable" to existing object when implementing a category.
Key is s simple pointer to private variable that you can declare as a module private by using:
static char SEARCH_INDEX_KEY = 0;

Public scope in Objective-C?

I’m sure this is a simple one, but it’s been elusive so far, and I’m stumped ...
How do I declare an Ivar so that it’s accessible from ALL Classes in a project?
[Don’t know if it matters, but the ivar in question is (an instance of) my Model class, whose data needs to be accessible to various view controllers.]
Best as I can tell from "The Scope of Instance Variables” in The Objective-C 2.0 Programming Language
... this would be by using the “#public” directive.
So I’ve tried this in the #interface block where the ivar is declared:
#interface ...
...
#public
ModelClass *theModel;
#end
... But when I try to refer to “theModel” in a different class, the compiler doesn’t auto-complete, and when I type it in anyway, the compiler shows:
“Error: ‘theModel’ undeclared (first use in this function)”.
I assume this is a question of Scope, and that I haven’t made the ivar available appropriately, but how? Somehow I need to access this, or make its pointer available somehow.
Any ideas would be VERY much appreciated. Many thanks!
Perhaps you forgot to put the instance variable inside the braces of the class where all instance variable declarations go?
#interface Foo : NSObject {
// other instance variable declarations
#public
ModelClass *theModel;
}
// method and property declarations
#end
Also, can you show us the code of how you are trying to access the instance variable from elsewhere? The proper syntax should be:
myFooInstance->theModel
where myFooInstance is a value of type "Foo *"
I make properties available to all views managed by a Tab Bar via a singleton representing my data model. This is efficient and allows all Views access to the data (as well as any other application elements. Creating the singleton is straightforward (there are a ton of examples on S.O.). The you just request the instance and get the property values you need.
Here is a framework fro creating the Singleton. The key points are the static instance and the fact that you do the initialization as [[self alloc] init];. This will ensure the object gets cleaned up correctly. All the methods at the bottom of the class are standard from the SDK Docs to make sure release calls are ignored (because the object is shared globally).
Singleton Boilerplate (ApplicationSettings.m):
static ApplicationSettings *sharedApplicationSettings = nil;
+ (ApplicationSettings*) getSharedApplicationSettings
{
#synchronized(self) {
if (sharedApplicationSettings == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedApplicationSettings;
}
+ (id)allocWithZone:(NSZone *)zone
{
#synchronized(self) {
if (sharedApplicationSettings == nil) {
sharedApplicationSettings = [super allocWithZone:zone];
return sharedApplicationSettings; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
You cannot access iVars from any other class.
You have to declare a getter/setter method to change or view a variable from another class - what you are really looking for are properties, that make it easier to define and access these getter/setter methods.
In your example above, you'd have the property defined just after the block that defines the local variable in the header file:
#property (nonatomic, retain) ModelClass *theModel;
In the implementation file you'd have the getter/setter created with the #synthesize statement just after the #implementation line:
#synthesize theModel;
Then if you have an instance of your class created, you access the class instance variable like so:
myInstance.theModel = [[[ModelClass alloc] init] autorelease];
The reason #public & #private are in there are to define visibility for subclasses (which, being extensions of that class type also get all the class local variables defined by a superclass), not for any random class.
The standard Objective-C way of doing it is to have a class method that returns the ivar
In your .h file:
+ (id)defaultModel;
and in your .m file:
static ModelClass * defaultModelInstance;
#implementation ModelClass
+ (id)defaultModel {
if (!defaultModelInstance) {
defaultModelInstance = [[ModelClass alloc] init];
}
return defaultModelInstance;
}
#end
although this will need tweaking if you need a specific ivar instead of just "a ivar that's always the same"
this type of design is used by many Cocoa classes i.e. [NSWorkspace sharedWorkspace]
Think a C global variable.
Adding:
extern ModelClass* theModel;
after the #end in the header will make the variable visible anywhere you include the header.
In the ModelClass.cpp file add:
ModelClass* theModel;
before the class implementation.
The variable will still have a value of nil until you allocate and initialize it though and you will be resposible for ensuring that it gets deallocated at the correct time.
THANK YOU ALL for the very helpful discussion on this topic! Clearly there are several ways to approach things here, so this is a very useful assortment of techniques.
Just to let y'all know that in researching this issue further, I ran across a couple of other very helpful pages, listed below. They include mention of the NSNotificationCenter, which I hadn't heard of before; as well as the idea of the "dependency injection" design pattern.
The idea is to keep "low coupling"(1) between the classes, making the code more modular & better for unit testing.
And while the 'notification' pattern sounds like a great idea, in this case it may be a bit overkill, considering that I only need ONE instance of the data model throughout the run of the app, and it doesn't change throughout.
Finally, even though the "#public" compiler directive is well-documented in Apple's Obj-C guide(2), I later found a fascinating edict in a different doc stating that it shouldn't be used! Quoted from Apple's own Cocoa Fundamentals(3):
"Give the proper scope to your instance variables. Never scope a variable as #public as this violates the principle of encapsulation. ..."
(Strange that they don't mention this in their 'Objective-C 2.0' guide where the directive is actually explained.)
Anyway, here are a couple of other links I found to be full of some great insights as well. FYI:
S.O.: "What’s the best way to
communicate between
viewcontrollers?"(4) <<
CocoaWithLove: "Five approaches to
listening, observing and notifying in
Cocoa"(5)
CocoaWithLove: "Singletons,
AppDelegates and top-level data"(6)
Hope these help. Anyway, thank you all again!
Best,
rond
P.S. Yikes! It won't let me post more than one inline hyperlink, so I'm listing them here instead. Obviously, they’re all prefixed by “http://” ... :O
(1): en.wikipedia.org/wiki/Coupling_(computer_science)
(2): developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html#//apple%5Fref/doc/uid/TP30001163-CH12-TPXREF127
(3): developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW12
(4): stackoverflow.com/questions/569940/whats-the-best-way-to-communicate-between-viewcontrollers
(5): cocoawithlove.com/2008/06/five-approaches-to-listening-observing.html
(6): cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html