Global instance of class - iphone

Im trying to make an instance of a class available in all methods in the .m file. Instead of doing this inside every method:
-(void)viewDidLoad
{
Class *c = [Class new];
}
My attempt in the .h file:
#interface RandomViewController : UIViewController
{
Class *c [Class new];
}
But It does'nt work, I get error
Expected ';' at end of declaration list
How would I make this possible?
Thanks

Create an instance variable, and set it up in your designated initializer. Here's a sample #implementation block.
#implementation RandomViewController {
// Instance variable names should start with an underscore, by convention.
Class *_c;
}
...
// Designated initializer for UIViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
_c = [[Class alloc] init];
}
return self;
}
...
- (void)someMethodThatNeedsAClassInstance
{
[_c doSomething];
}
If you're not using ARC, you'll need to add [_c release] to your dealloc implementation.
Now, in every method in your class, you may refer to _c and get the instance you created in the initializer. As a side note, this isn't really a 'global' instance - it is per-object. Each individual view controller you create will have its own instance of _c. Also, an even better approach is to declare a property and not bother declaring an instance variable at all.

In .h file:
#interface RandomViewController : UIViewController
{
Class *c;
}
In .m file:
-(void)viewDidLoad
{
c = [[Class alloc] init];
}

what do it do the class method? if return void:
Class.h file:
#interface Class: NSObject
{
}
- (void)new;
RandomViewController.h
#interface RandomViewController : UIViewController
{
Class *c;
}
RandomViewController.m file
-(void)viewDidLoad
{
c = [[Class alloc] init];
//call the method
[c new];
}

Related

Global Functions Objective C

I am trying to write a global function however keep getting the error "No visible interface...." when i try and call it.
Popover.h
#import <Foundation/Foundation.h>
#interface Popover : NSObject{}
- (void)PopoverPlay;
#end
Popover.m
#import "Popover.h"
#implementation Popover
- (void)PopoverPlay{
NSLog(#"I Work");
}
#end
In View.m i am adding the import "Popover.h" but i cant get rid of the error message when i try and run.
#import "View.h"
#import <QuartzCore/QuartzCore.h>
#import "Popover.h"
#interface View ()
{
}
#end
#implementation View
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad{
[super viewDidLoad];
}
- (IBAction)ButtonPress {
[self PopoverPlay];
}
Any ideas
Thanks
The code you've shown is the declaration and definition of a class that contains a single instance method. To use it, you'll need to allocate an instance of Popover with code that looks something like:
#import "Popover.h"
//...
Popover *pop = [[Popover alloc] init];
[pop PopoverPlay];
//...
When people talk about "global functions" they don't usually mean instance methods (or even class methods), so I doubt this is quite what you're after. Perhaps you mean an actual function that you can call from other parts of your code? You'd do that the same way you do in C:
void foo(void);
void foo(void)
{
NSLog(#"This works");
}
If you add the prototype (first line) to a header file, you can use the function anywhere in any file that includes that header.
Update:
- (IBAction)ButtonPress {
[self PopoverPlay];
}
The problem here is that you're sending -PopoverPlay to self, but self in this case represents an instance of View. You need to send -PopoverPlay to an instance of the class that implements it, which is Popover. See my example above. (BTW, your interface and implementation don't match: one is PupilView and the other is View.)
To call the method you wrote, you need to do something like:
Popover *myPopover = [[Popover alloc] init];
[myPopover PopoverPlay];
What you have is an instance method. Because your method doesn't rely on any instance variables, you could make it a class method by changing the - to +:
+ (void)PopoverPlay;
and
+ (void)PopoverPlay{
Then you don't need to initialize a new Popover; you can just call:
[Popover PopoverPlay];

What is the use of init in this singleton class..?

#Interface
//
// Created by macbook on 31.05.12.
//
// To change the template use AppCode | Preferences | File Templates.
//
#import <Foundation/Foundation.h>
#interface CESettings : NSObject
+ (CESettings *)sharedInstance;
- (void)save;
#end
#Implementation
//
// Created by macbook on 31.05.12.
//
// To change the template use AppCode | Preferences | File Templates.
//
#import "CESettings.h"
#interface CESettings ()
#property(nonatomic, strong) NSUserDefaults *userDefaults;
#end
#implementation CESettings
#synthesize userDefaults = _userDefaults;
#pragma mark - Singleton
static CESettings *_instance = nil;
+ (CESettings *)sharedInstance {
#synchronized (self) {
if (_instance == nil) {
_instance = [self new];
}
}
return _instance;
}
- (id)init {
self = [super init];
if (self) {
self.userDefaults = [NSUserDefaults standardUserDefaults];
}
return self;
}
#pragma mark - Methods
- (void)save {
[self.userDefaults synchronize];
}
#end
I have a class used for settings in an app. The class has a method for creating singleton and an init method as well. What is the use for both..? I think if the sharedInstance method is there , there is no need for the init... please correct me if I am wrong..
Any help is appreciated.
The init method is what gets called by new in the call of [self new]. It is essentially the same as
_instance = [[CESettings alloc] init];
but takes less typing and avoids hard-coding the name of the CESettings class.
A better way of implementing singleton is using dispatch_once, like this:
+ (CESettings*)sharedInstance
{
static dispatch_once_t once;
static CESettings *_instance;
dispatch_once(&once, ^ { _instance = [self new]; });
return _instance;
}
From the documentation of NSObject:
+ (id)new
Allocates a new instance of the receiving class, sends it an init
message, and returns the initialized object.
You're calling [self new] in your singleton creator method, which in turn will allocate a new instance and send it an init message.
the sharedInstance class method is only responsible for allocating and initing ONE object and then always returning that.
BUT
you dont have go through that method you can call alloc init yourself and it will also work
so init is needed to keep the semantics of how alloc/init should work

ios how can access and modify variable from diffent class?

I have the following:
Class 1:
.h file:
#interface class1 : UIViewController
#property (assign,nonatomic) int number;
.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
number=1;
}
Class2:
.h file:
#interface class2 : UIView{
class1 *Controller;
}
#property (retain,nonatomic) class1 *controller;
but if access the number variable from anywhere in the second class the value is 0 any of you knows why?
Is the class already open and retained somewhere (i.e. your navigation stack)? If so you can then safely access and modify variables because they are already initialized. If not that's probably why you're getting 0 returned.
Another way is to create and maintain a data singleton that all view controllers can draw data from easily and you can then reference that data singleton to modify and change values.
Assuming the view controller is already initialized and active you can then do something like this:
MyViewController *vc = [[MyViewController alloc] init];
[vc setValue:#"100"];
You can use appDelegate method to access the variable from some other class,
example,
in your class2:
.m file
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
Controller = appDelegate.viewControllerClass1;
}
return self;
}
in AppDelegate Class, .m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewControllerClass1 = [[[Class1 alloc] init] autorelease];
NavigationController=[[UINavigationController alloc]initWithRootViewController:self.viewControllerClass1];
[self.window makeKeyAndVisible];
return YES;
}

Resolving undeclared Indentifer from Class (Part 2)

I want to created and populate an Array in a class and then use the content in the array in the main program... As an example I'll use a list of names of the US States...
This is an update on the original question that is halfway resolved and has been contented for clarity so you can see the code properly.
ArrayStates.h
#import <Foundation/Foundation.h>
#interface ArrayStates : NSObject
#end
ArrayStates.m
#import "ArrayStates.h"
#interface ArrayStates() { NSMutableArray *listOfStates; }
#implementation ArrayStates
- (void)viewDidLoad {
//---initialize the array---
listOfStates = [[NSMutableArray alloc] init];
//---add items---
[listOfStates addObject:#"ALABAMA"];
[listOfStates addObject:#"WYOMING"];
[super viewDidLoad];
}
#end
This is updated code from the previous Question but it still generates a Missing end error on the implementation line, the void wants a . after method prototype and you still can't reference the object in the main program.
I believe altering the ordering if the interface and implementation differentiates whether the array can be accessed within or outside the class (thanks to iHungry for that).
Create a property like Mundi said in the .h, and then just import the ArrayStates.h where ever you need to access the array. You can then make an instance of class ArrayStates, (create an object and alloc-init), and then use that object to access its listOfStates property.
// in ArrayStates.h
#interface ArrayStates : NSObject
#property NSMutableArray *listOfStates;
#end
// in ArrayStates.m
#implementation ArrayStates
#synthesize listOfStates;
//...
-(void)viewDidLoad {
[super viewDidLoad];
listOfStates = [[NSMutableArray alloc] init];
}
#end
// in some other class
ArrayStates *states = [[ArrayStates alloc] init];
NSLog(#"%#", states.listOfStates);
In the viewDidLoad method, you must call super first.
By the way, your ArrayStates class is a subclass of NSObject so its method viewDidLoad will not gonna be called!

When to release a class with delegates

A quick question to delegates. Lets say, CLASSA has a delegate defined:
#protocol MyDelegate
-(void) didFinishUploading;
#end
In CLASSB I create an instance of CLASS A
-(void) doPost {
CLASSA *uploader = [[CLASSA alloc] init];
uploader.delegate = self; // this means CLASSB has to implement the delegate
uploader.post;
}
and also in CLASSB:
-(void)didFinishUploding {
}
So when do I have to release the uploader? Because when I release it in doPost, it is not valid anymore in didFinishUploading.
Thanks
Release it in didFinishUploding. Put CLASSA * uploader in the instance variables of CLASSB to allow for that.
Instead of creating CLASSA instance in doPost method.
It is better to create CLASSA *uploader = [[CLASSA alloc] init]; in the init method and release uploader in dealloc.
make uploader as member variable.
-(id) init
{
self = [super init];
if(self)
{
uploader = [[CLASSA alloc] init];
uploader.delegate = self;
}
retrurn self;
}
-(void) doPost
{
uploader.post;
}
-(void)didFinishUploding
{
uploader.delegate = nil;
//your code
}
-(void) dealloc
{
[uploader release];
[super dealloc];
}