iOS - how do I create a "utility" class that all my controllers can call - objective-c

I am new to iOS and obective-c so I am not too sure how to best accomplish this seemingly simple task.
What I want is to make a class that looks like this in pseudocode:
class UtilityClass
{
// Have a method that I can pass parameters to
String doCalculation ( String art1 , String arg2 )
{
return arg1 + arg2;
}
}
My uncertainty is:
1) xCode seems to be inclined to lay out my file structure in a relatively flat way. So should I make a utils directory and have this file be under utils/fileName ? Usually I am kind of used to having at least some src directory, but so far I have not been prompted by anything to create one.
2) How do I import and call this class/function from my controllers?
Thanks,
Alex

Just create a new group called Utilities, and then create your class inside it. Like,
utils.h
utils.m
Later in your ViewController's header file just add.
#import "utils.h"
if this utils class is used by many controllers in very fat project then, find a file called, Should be inside supporting files group.
YourAppName-Prefix.pch
In that file you have a code block like this,
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#endif
Just edit this block and add your utils.h reference here, In this way your entire project can create utils object without explicitly importing into their own header.
Edit like this.,
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "utils.h"
#endif

First of all create a new File in Xcode and uncheck xib file. Name the Project as you like . and extend it from NSObject .
for creating static method you have to replace function starting - to + like
interface. class
#interface Utility : NSObject
+ (int)getNumber;
+ (void)setNumber:(int)number;
#end
.m class
#import "Utility.h"
#implementation Utility
static int number = 1;
+ (int)getNumber {
return number;
}
+ (void)setNumber:(int)newNumber {
number = newNumber;
}
+ (id)alloc {
[NSException raise:#"Cannot be instantiated!" format:#"Static class 'ClassName' cannot be instantiated!"];
return nil;
}
#end
call it in any other ViewController like
NSLog(#"number = %d", [Utility getNumber]);
[Utility setNumber:3];
NSLog(#"number = %d", [Utility getNumber]);
for details..

Where you store the files is up to you, just make sure XCode knows where to find them. The class itself should be made like any other Objective C class, just make it inherit from NSObject instead of one of the graphical classes:
// MyClass.h
#interface MyClass : NSObject {
int instanceVar;
}
#property (nonatomic, assign) int property;
#end
// MyClass.m
#import "MyClass.h"
#implementation MyClass
#synthesize property;
-(id) init {
...
}
-(int) function {
...
}
#end
To use the class in another file, just import the header like any other class
#import "MyClass.h"

Related

Accessing category method in original Objective C class

I have a class for which I have created a category. Now I want to access category method inside original class but I am getting error:
error: instance method '-hasSound' not found (return type
defaults to 'id') [-Werror,-Wobjc-method-access]
// Animal.h
#interface Animal: NSObject
- (void)sound;
#end
// Animal.m
#import "Animal+Additions.h"
#implementation Animal
- (void)sound {
[self hasSound];
}
#end
// Animal+Additions.h
#interface Animal (Additions)
- (BOOL)hasSound;
#end
// Animal+Additions.h
#implementation Animal (Additions)
- (BOOL) hasSound {
return YES;
}
#end
I have been doing same thing in Swift but not sure how to achieve the same thing in Objective C.
Category and original class are in separate files. I have imported Category interface file inside original class but that didn't work.
You have not shown sufficient #import statements, so I have to assume they don't exist. You need them.
Another possible issue is that, at least according to your comments, you seem to have two Animal+Additions.h files but no Animal+Additions.m file.
This complete code in four files compiles for me:
// Animal.h
#import <Foundation/Foundation.h>
#interface Animal: NSObject
- (void)sound;
#end
// Animal.m
#import "Animal.h"
#import "Animal+Additions.h"
#implementation Animal
- (void)sound {
[self hasSound];
}
#end
// Animal+Additions.h
#import "Animal.h"
#interface Animal (Additions)
- (BOOL)hasSound;
#end
// Animal+Additions.m
#import "Animal+Additions.h"
#implementation Animal (Additions)
- (BOOL) hasSound {
return YES;
}
#end
Note all the #import statements, and note that the Animal.m file must be part of the target.

Accessing interface method defined in .m file

MyClass.h file
#import <Foundation/Foundation.h>
#interface MyClass : NSObject
{
// This is the Place of Instance Variable
}
- (void)thePublicMethod;
#end
MyClass.m file
#import "MyClass.h"
#interface MyClass()
- (void)thePrivateMethod;
#end
#implementation MyClass
-(void)thePublicMethod {
NSLog(#"Public Method Called");
}
- (void)thePrivateMethod {
NSLog(#"Private Method Called");
}
#end
The main.m file
#import <Foundation/Foundation.h>
#import "MyClass.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
MyClass *myObj = [[MyClass alloc] init];
[myObj thePublicMethod];
// [myObj thePrivateMethod];
}
return 0;
}
since “Private” methods can be created by defining them in a class’s implementation file while omitting them from its interface file.
i want to access thePrivateMethod from main.m and also can i call thePrivateMethod() from thePublicMethod() is it possible and how ?
If you want to access an internal method from somewhere other than the class's implementation, then you need to truly declare it as a private method.
Move that class extension to its own header file, say MyClass_Private.h. Then #import that header into both main.m and MyClass.m.
I.e. move this:
#interface MyClass()
- (void)thePrivateMethod;
#end
Into a file called MyClass_Private.h and then #import "MyClass_Private.h" in both your MyClass.m and main.m files.
Internal means only used in the innards of this framework or class.
Private means may be used by this framework or the class, but may be exposed to clients that are more intimately tied to the class than through Public API. Typically reserved for framework authors on large scale systems (like the OS).
Public means may be used anywhere by any client of the class.
No matter how or where or IF you declare a method, at all.. If it exists.. calling it is as simple as
[myInstance performSelector:NSSelectorFromString(#"yourSuperSecretMethod:")
withObject:myKillerObject];
If the method got compiled.. It will get called. There is no "hiding" it. Even if not declared, the runtime "gives up" this information to any interested party. #see class-dump, if interested in learning more.

How to simulate protected properties and methods in objective-c [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Protected methods in objective-c
The way to declare private properties is simple.
You declare that in extension that's declared in .m files.
Say I want to declare protected properties and access it from the class and subclass.
This is what I tried:
//
// BGGoogleMap+protected.h
//
//
#import "BGGoogleMap.h"
#interface BGGoogleMap ()
#property (strong,nonatomic) NSString * protectedHello;
#end
That one is compile. Then I added:
#import "BGGoogleMap+protected.h"
#implementation BGGoogleMap ()
-(NSString *) protectedHello
{
return _
}
#end
Problem starts. I can't implement class extension outside the original .m files it seems. Xcode will demand something inside that bracket.
If I do
#import "BGGoogleMap+protected.h"
#implementation BGGoogleMap (protected)
-(NSString *) protectedHello
{
return _
}
#end
I cannot access the ivar of _protectedHello declared in BGGoogleMap+protected.h
Of course I can use regular category rather than extension, but that means I can't have protected properties.
So what should I do?
The Objective-C Programming Language says this:
Class extensions are like anonymous categories, except that the methods they declare must be implemented in the main #implementation block for the corresponding class.
So you could just implement your class extension's methods in the class's main #implementation. That is the simplest solution.
A more complicated solution is to declare your “protected” messages and properties in a category, and declare any instance variables for that category in a class extension. Here's the category:
BGGoogleMap+protected.h
#import "BGGoogleMap.h"
#interface BGGoogleMap (protected)
#property (nonatomic) NSString * protectedHello;
#end
Since a category cannot add an instance variable to hold protectedHello, we need a class extension also:
`BGGoogleMap_protectedInstanceVariables.h'
#import "BGGoogleMap.h"
#interface BGGoogleMap () {
NSString *_protectedHello;
}
#end
We need to include the class extension in the main #implementation file so that the compiler will emit the instance variable in the .o file:
BGGoogleMap.m
#import "BGGoogleMap.h"
#import "BGGoogleMap_protectedInstanceVariables.h"
#implementation BGGoogleMap
...
And we need to include the class extension in the category #implementation file so that the category methods can access the instance variables. Since we declared the protectedHello property in a category, the compiler will not synthesize the setter and getter method. We have to write them by hand:
BGGoogleMap+protected.m
#import "BGGoogleMap+protected.h"
#implementation BGGoogleMap (protected)
- (void)setProtectedHello:(NSString *)newValue {
_protectedHello = newValue; // assuming ARC
}
- (NSString *)protectedHello {
return _protectedHello;
}
#end
Subclasses should import BGGoogleMap+protected.h to be able to use the protectedHello property. They should not import BGGoogleMap_protectedInstanceVariables.h because the instance variables should be treated as private to the base class. If you ship a static library without source code, and you want users of the library to be able to subclass BGGoogleMap, ship the BGGoogleMap.h and BGGoogleMap+protected.h headers, but don't ship the BGGoogleMap_protectedInstanceVariables.h header.
I wish I could tell you otherwise but you just can't. See this question for more information: Protected methods in Objective-C.
I am not sure, what you want to do? Something Hacking or Cracking of Data Abstraction out of OOPS concept?
Extensions are used to add properties. You have successfully added private property as in
#import "BGGoogleMap.h"
#interface BGGoogleMap ()
#property (strong,nonatomic) NSString * protectedHello;
#end
What are you doing in this ?
#import "BGGoogleMap+protected.h"
#implementation BGGoogleMap ()
-(NSString *) protectedHello
{
return _
}
#end
You have extended a class, now you are again implementing same class !!! Twice!!! And category only comes with .h file. I guess you are creating yourself a .m file, that not acceptable.
Private properties cant be accessed outside the class, it can be accessed only from the base class or subclass. That is what the error is.
I can't implement class extension outside the original .m files it seems.
Yes this is abstraction and data hiding of Objective-c !!!

subclassing issue with static constant variable in iOS

I have Class A and Class B.
Class B subclasses Class A
Class A has a static constant NSString variable
In a method of Class B I need to use the static constant NSString variable of Class A. What are my options ?
I tried declaring the same thing again, but caused problem (internal inconsistency), tried without using (says, variable undeclared).
Any idea how I can solve this problem ?
Thanks.
Make a class method returning that constant, like this:
+(NSString*) constString {
return myConstString;
}
You can declare static constant strings in the .h file. That way they are public and can be used by other classes that import the header file, including your subclass.
Alternatively, you can declare a reference to the string in your Class B using extern:
extern NSString *const MyString;
That basically tells the compiler that the value of that string is defined elsewhere in the code and it doesn't have to worry about it.
By "Class A has a static constant NSString variable", I assume you're referring to having something like the following defined in your Class A .m file:
static NSString * const MyString = #"MyString";
#implementation ClassA
#end
To allow Class A and its subclasses to see the value, you can do something like this:
MDClassAPrivate.h:
#import <Foundation/Foundation.h>
static NSString * const MDBlahBlahKey = #"MDBlahBlah";
MDClassA.h:
#import <Foundation/Foundation.h>
#interface MDClassA : NSObject {
}
#end
MDClassA.m:
#import "MDClassA.h"
#import "MDClassAPrivate.h"
#implementation MDClassA
#end
MDClassB.h:
#import "MDClassA.h"
#interface MDClassB : MDClassA {
}
#end
MDClassB.m:
#import "MDClassB.h"
#import "MDClassAPrivate.h"
#implementation MDClassB
#end
By moving the static const variables to a separate file, you can allow any class to import them in the implementation file.
My personal solution to this problem would be a pseudo-protected method that returns the constant string.
// ClassA.m
#interface ClassA ()
- (NSString *)constantString;
#end
#implementation ClassA
- (NSString *)constantString {
return #"MyConstantString";
}
#end
Then following on into your subclass:
// ClassB.m
#interface ClassA ()
// This is a method redeclaration to avoid build warnings
- (NSString *)constantString;
#end
#implementation ClassB
- (void)someMethod {
NSString *theConstantString = [self constantString];
// do stuff...
}
#end
The assumption here is that your constant string really is constant, if you want it to be dynamic you would need to modify this solution slightly, but it can still handle it.
You can use 'userDefaults' to set a value that is accessible in the whole application.
[[NSUserDefaults standardUserDefaults] setObject:object forKey:#"objectKey"];

Dynamically typed class generates compiler warnings on method selection

Perhaps this is the wrong way to go about this, but it seems like such a clean and workable approach that I wonder how I can make the compiler warning go away?
#interface SomeView : UIView {
NSString *stringOfsomeImportance;
RelatedClass *niftyService;
}
#property (nonatomic, copy) NSString * stringOfnoImportance;
#property (nonatomic, retain) RelatedClass *niftyService;
#implementation
-(void)someMethod;
-(void)otherMethods;
#implementation RelatedClass *pvSomeObj = [[RelatedClass alloc] initWithSender:self];
[self setNiftyService:pvSomeObj];
Now, looking at the RelatedClass implementations...
#interface RelatedClass : NSObject {
id thesender;
#property (nonatomic, retain) id thesender;
#implementation
[thesender otherMethods]; // this generates a compiler warning
// that otherMethods cannot be found
// in SomeView, though it *is* found
// and seems to execute just fine
This seems like a valid approach, so I'm left wondering why the warning?
Is there a way to better "explain" this to the compiler?
Could someone kindly share if this type of linkage is encouraged or if there is a better way to link two related, interdependent classes that need to communicate with one another?
I can't statically declare the sender object (SomeView) in RelatedClass because that seems to cause a recursion problem, as SomeView is defined with RelatedClass as a member...
Any suggestions?
You can define a protocol and say that your thesender object must conform to it:
#protocol MyProtocol
-(void)otherMethods;
#end
#interface RelatedClass : NSObject {
id<MyProtocol> thesender; // Now compiler knows that thesender must respond
// to otherMethods and won't generate warnings
}
You can send otherMethods message another way (you may need to define theSender as NSObject here):
if ([theSender respondsToSelector:#selector(otherMethods)])
[theSender performSelector:#selector(otherMethods)];
Edit: Actually you can also define thesender as SomeView* in your RelatedClass using forward class declaration:
//SomeView.h
#class RelatedClass;
#interface SomeView : UIView {
RelatedClass *niftyService;
}
// then include RelatedClass.h in SomeView.m
//RelatedView.h
#class SomeView;
#interface RelatedClass : NSObject {
SomeView* thesender;
}
// then include SomeView.h in RelatedClass.m
In your headers, you can forward declare classes that you want to use. In your implementation files, you can include the full header of those classes that you forward-declared.
For example:
SomeView.h
#import <FrameworkHeader.h>
// Here, you are saying that there is a class called RelatedClass, but it will be
// defined later.
#class RelatedClass;
#interface SomeView : UIView
{
RelatedClass *niftyService;
}
#end
SomeView.m
#import "SomeView.h"
#import "RelatedClass.h"
// By including "RelatedClass.h" you have fulfilled the forward declaration.
#implementation SomeView
// Can use "RelatedClass" methods from within here without warnings.
#end
RelatedClass.h
#import <FrameworkHeader.h>
#class SomeView;
#interface RelatedClass
{
SomeView *someView;
}
// methods
#end
RelatedClass.m
#import "RelatedClass.h"
#import "SomeView.h"
#implementation RelatedClass
// Can use "SomeView" methods from within here without warnings.
#end
id thesender = ....;
[thesender otherMethods]; // this generates a compiler warning
// that otherMethods cannot be found
// in SomeView, though it *is* found
// and seems to execute just fine
For the above to generate the warning as you describe, it is entirely because the method -otherMethods has not been declared someplace where the compiler sees the declaration before attempting to compile the call site.
That is, the declaration of the method:
- (void) otherMethods;
Must appear in a header file that is imported -- directly or indirectly -- by the implementation file compiling that particular call site or the method declaration must appear in the #implementation before the call site.