How to make a ConstantList Class in Objective C - iphone

How to make a ConstantList class in Objective C of an application which could be accessible to all the classes who are using constants.
like in Actionscript we do:
public class ConstantList
{
public static const EVENT_CHANGE:String = "event_change";
}
Or what is the best approach to handle application constant.
Regards
Ranjan

You can use global constants, like the following:
//MyConstants.m
NSString * const EVENT_CHANGE = #"event_change";
// MyConstants.h
extern NSString* const EVENT_CHANGE;
Now include MyConstants.h header to your implementation file and you can use EVENT_CHANGE constant string in it

I would recommend Vladimir's approach.
Just for completeness: You can do it as a class like this:
#interface Constants : NSObject {
}
+ (NSString*)aConstantString;
#end
#implementation Constants
+ (NSString*)aConstantString {
return #"This is always the same and accessible from everywhere";
}
#end
You access the value like:
NSString* string = [Constants aConstantString];

Related

ios - How to declare static variable? [duplicate]

This question already has answers here:
What's the meaning of static variables in an implementation of an interface?
(4 answers)
Closed 9 years ago.
Static Variable declared in C# like this :
private const string Host = "http://80dfgf7c22634nbbfb82339d46.cloudapp.net/";
private const string ServiceEndPoint = "DownloadService.svc/";
private const string ServiceBaseUrl = Host + ServiceEndPoint;
public static readonly string RegisteredCourse = ServiceBaseUrl + "RegisteredCourses";
public static readonly string AvailableCourses = ServiceBaseUrl + "Courses";
public static readonly string Register = ServiceBaseUrl + "Register?course={0}";
How to call this static variable in another class ?
Answer : use the static keyword.
Syntax : static ClassName *const variableName = nil; ( Updated [ Added const] as per the Comment by Abizern )
Reason for update ( As per the comments by "Till " ) :
static when being used on a variable within a function/method will preserve its state even when the scope of that variable is left. When being used outside any function/method, it will make that variable invisible to other source files - it will be visible within that implementation file only when being used outside any function/method.
Hence a const with static helps the compiler to optimize it accordingly.
If you need more explanation on use of const with static, I found one beautiful link here : const static.
Use:
You might have seen the use of "static" keyword in your tableview's delegate - cellForRowAtIndexPath:
static NSString *CellIdentifier = #"reuseStaticIdentifier";
static NSString *aString = #""; // Editable from within .m file
NSString * const kAddressKey = #"address"; // Constant, visible within .m file
// in header file
extern NSString * const kAddressKey; // Public constant. Use this for e.g. dictionary keys.
To my knowledge public statics aren't a built-in feature of Objective-C. You can work around this by making a public class method that returns the static variable:
//.h
+ (NSString *)stringVariable;
//.m
static NSString * aString;
+ (NSString *)stringVariable
{
return aString;
}
Most static objects can't be initialized at compile time (I think only strings actually). If you need to initialize them, you can do so in the + (void)initialize method, which lazily gets called whenever that class is first referenced.
static UIFont *globalFont;
+ (void)initialize
{
// Prevent duplicate initialize http://www.mikeash.com/pyblog/friday-qa-2009-05-22-objective-c-class-loading-and-initialization.html
if (self == [ClassName class]) {
globalFont = [UIFont systemFontOfSize:12];
}
}
Objective C is super set of C/C++ , so for static it follows C++/C convention, you should be able to use it
static <<datatype>> <<variableName>> = initialization
Hoping you would have tried this way , have you got any error, if yes, please add more clarity in your question
if thats case with NSString use following,
static NSString *pString = #"InitialValue";
and if you have to modify NSString in your code, make sure it must be NSMutableString.
Hope that's help ...

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

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;
}

Cocoa : how do you name your init parameters for not interfering with ivars?

Let's begin with an example :
#interface myClass : NSObject {
NSString * title;
}
-(id)initWithTitle:(NSString*)title;
Compiler doesn't like this because title init parameter hides myClass title ivar.
But i don't like these options :
-(id)initWithTitle:(NSString*)t;
-(id)initWithTitle:(NSString*)myTitle;
-(id)initWithTitle:(NSString*)_title;
So that's a poll: what's your convention?
Some people prefer calling their ivars _title or title_ and then they can just use title as parameter name in functions. Or you just call it aTitle or newTitle. There is no right or wrong way to do it.
I prefer to use -(id)initWithTitle:(NSString *)aTitle;.
I currently use pTitle, but used inTitle for years.

objective-c++: is it possible to define a c++ class with a method which returns objective-c classes and uses covariant returns?

**Edit: this only happens with llvm; gcc supports this just fine.
Consider the following.
Objective-c classes A and B.
B is a subclass of A.
We want a c++ hiearchy that looks like:
class X {
//...
public:
virtual A* getFoo();
};
class Y : public X {
//...
public:
B* getFoo();
};
However, if you do this, you'll get an error, as the Objective-c types confuse the c++ compiler:
error: virtual function 'getFoo' has a different return type ('Y *') than the function it overrides (which has return type 'X *')
I'm wondering if anyone has a workaround for this? (Obviously, long term, we'll be moving away from Objective-c classes, but that's not today).
P.S. This seems like the most similar question I could find, but I'm pretty sure it's a different problem.
This compiles and runs fine for me:
#import <Cocoa/Cocoa.h>
#interface A : NSObject
- (NSString*) bar;
#end
#implementation A
- (NSString*) bar
{
return #"";
}
#end
#interface B : A
#end
#implementation B
- (NSString*) bar
{
return #"!!!";
}
#end
class X {
//...
public:
virtual A* getFoo() = 0;
};
class Y : public X {
//...
public:
virtual B* getFoo() { return [B new]; }
};
int main (int argc, char const *argv[])
{
X* x = new Y;
NSLog(#"%#", [x->getFoo() bar]); // >> !!!
return 0;
}
Maybe your problem was that you didn't import B's header file into the file defining Y? You can't get covariance (in c++, at least) on incomplete classes, as the compiler needs to know that B inherits from A in order to compile Y.
Anyway, to answer your question, looks like it is possible to do this.

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;