No access to global instance (build by factory) on iOS - objective-c

this is a follow-up question to my last one here: iOS: Initialise object at start of application for all controllers to use .
I have set my application up as follows (ignore the DB Prefix):
DBFactoryClass // Built a DataManaging Object for later use in the app
DBDataModel // Is created by the factory, holds all data & access methods
DBViewControllerA // Will show some of the data that DBDataModel holds
moreViewControllers that will need access to the same DBDataModel Object
i will go step by step through the application, and then post the problem in the end
AppDelegate.h
#import "DBFactoryClass.h"
AppDelegate.m
- (BOOL)...didFinishLaunching...
{
DBFactoryClass *FACTORY = [[DBFactoryClass alloc ]init ];
return YES;
}
DBFactoryClass.h
#import <Foundation/Foundation.h>
#import "DBDataModel.h"
#interface DBFactoryClass : NSObject
#property (strong) DBDataModel *DATAMODEL;
#end
DBFactoryClass.m
#import "DBFactoryClass.h"
#implementation DBFactoryClass
#synthesize DATAMODEL;
-(id)init{
self = [super init];
[self setDATAMODEL:[[DBDataModel alloc]init ]];
return self;
}
#end
ViewControllerA.h
#import <UIKit/UIKit.h>
#import "DBDataModel.h"
#class DBDataModel;
#interface todayViewController : UIViewController
#property (strong)DBDataModel *DATAMODEL;
#property (weak, nonatomic) IBOutlet UILabel *testLabel;
#end
ViewControllerA.m
#import "todayViewController.h"
#implementation todayViewController
#synthesize testLabel;
#synthesize DATAMODEL;
- (void)viewDidLoad
{
todaySpentLabel.text = [[DATAMODEL test]stringValue]; // read testdata
}
#end
DBDataModel.h
#import <Foundation/Foundation.h>
#interface DBDataModel : NSObject
#property (nonatomic, retain) NSNumber* test;
#end
DBDataModel.m
#import "DBDataModel.h"
#implementation DBDataModel
#synthesize test;
-(id)init{
test = [[NSNumber alloc]initWithInt:4]; // only a testvalue
return self;
}
#end
the app builds fine, and starts up but the label stays blank. so either the object does not exist (but i guess this would result in an error message), or something else is wrong with my setup. any thoughts?

Two notes:
Your have a shotgun approach to asking questions: everytime you hit a stumbling block, you ask a question and if the answer does not work immediately, you ask another one. You have to spend some energy in between the questions debugging and poking into the code on your own, otherwise you will depend on the external help forever.
Use the common coding style please. CAPS are reserved for macros.
Now to the code:
- (BOOL) …didFinishLaunching…
{
DBFactoryClass *factory = [[DBFactoryClass alloc] init];
return YES;
}
This simply creates an instance of the DBFactoryClass and then throws it away. In other words, it’s essentially a no-op. Judging by the comments in the previous answer you create the controllers using the Storyboard feature. How are they supposed to receive the reference to the data model? The reference isn’t going to show up by magic, you have to assign it somewhere.
I’m not familiar with the Storyboard feature. The way I would do it is to create the view controllers using separate XIB files, then you can create the controller instances in the Factory class and pass them the needed reference to the model. In the end the application delegate would create the factory, ask it to assemble the main controller and then set it as the root view controller for the window. Just like in my sample project. It’s possible that there’s a way to make it work with storyboards, but as I said, I am not familiar with them.

Related

In Objective-C, how to make #property's accessible to other classes?

The original question remains below this update:
So further research indicates that my
"...missing setter or instance variable"
log messages are due to an unhinged .xib.
I originally thought that might be the case which is why I went through the process of re-connecting the outlets and properties in the graphic interface builder, but that seems to have been insufficient to repair the connections.
I restored the outlets as properties rather than iVars and reconnected again, still to no avail. So I'm in the process of remaking the .xib's from scratch. Stay tuned for the results.
Original question follows:
Having declared and synthesized properties in parent and sheet classes, and attempted therein to access the properties by their respective class.property names, Xcode rejects the code.
I posted a similar question recently and deleted it after being told there was not enough info to make a response, so I include here below a mini-app which shows how the relevant setup was in the real app of over 2000 lines of Objective-C, which built and ran properly before I attempted to add the Parent / Sheet properties feature.
I've indicated the compiler error messages with a prefix of ////. When I comment out the erroneous lines, the app with its .xib's builds and runs, dysfunctionally of course.
ParentClass.h
// ParentClass stuff belongs in the original main window controller
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#interface ParentClass : NSObject
{
IBOutlet NSTextField * messageTextField;
IBOutlet NSButton * proceedButton;
}
#property (assign) IBOutlet NSWindow * window;
#property (strong) NSMutableString * parentPropInfo;
- (IBAction) awakeFromNib;
- (IBAction) doCreate:(id)sender;
#end
ParentClass.m
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import "ParentDelegate.h"
#import "ParentClass.h"
#import "SheetClass.h"
#implementation ParentClass
ParentDelegate * MyDelegate; // only confirms termination requests
NSWindowController * SheetController;
#synthesize parentPropInfo;
- (IBAction)awakeFromNib {
MyDelegate = [NSApplication sharedApplication].delegate;
MyDelegate.ParentController = self; // BTW, this property assignment works!
SheetController = [[SheetClass alloc] initWithWindowNibName: #"SheetClass"];
messageTextField.stringValue = #"Click Proceed button";
}
- (IBAction)doProceed*emphasized text*:(id)sender {
parentPropInfo = #"Hello!".mutableCopy; // to be read by the sheet
[NSApp runModalForWindow:SheetController.window];
// Sheet is active now until it issues stopModal, then:
messageTextField.stringValue = SheetController.sheetPropInfo; // set by the sheet
////above gets ERROR "Property sheetPropInfo not found on object of type 'NSWindowController *'"
messageTextField.stringValue = SheetController.window.sheetPropInfo;
////above gets ERROR "Property sheetPropInfo not found on object of type 'NSWindow *'"
[NSApp endSheet: SheetController.window];
[SheetController.window orderOut:self];
}
#end
SheetClass.h
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import "ParentClass.h"
#interface SheetClass : NSWindowController
{
IBOutlet NSTextField * propTextField;
IBOutlet NSButton * cancelButton;
}
#property (assign) IBOutlet NSWindow * window;
#property NSMutableString * sheetPropInfo;
- (IBAction)awakeFromNib;
- (IBAction)doCancel:(id)sender;
#end
SheetClass.m
#import "SheetClass.h"
#import "ParentClass.h"
#implementation SheetClass
#synthesize sheetPropInfo;
- (IBAction)awakeFromNib {
propTextField.stringValue = self.window.sheetParent.parentPropInfo; // set by the parent
////above gets ERROR "Property parentPropInfo not found on object of type 'NSWindow *'"
sheetPropInfo = #"Goodbye!".mutableCopy; // to be read by the parent
}
- (IBAction)doCancel:(id)sender {
[NSApp stopModal];
}
#end
I can find nothing in Apple documentation or extensive (three weeks now!) online search to offer any insight as to my abysmal ignorance. I apologize for the overwhelming batch of code needed to illustrate my problem! Where shall I obtain the information I need?
The error messages are perfectly clear. Just read them and think about them. Let's just take the first one. You are saying:
messageTextField.stringValue = SheetController.sheetPropInfo;
...and getting this response from the compiler:
// Property sheetPropInfo not found on object of type 'NSWindowController *'
Well, think about the expression SheetController.sheetPropInfo and why the compiler cannot make sense of it. You have declared SheetController as follows:
NSWindowController * SheetController;
So that is all the compiler knows: SheetController is an NSWindowController. Well, sure enough, just as the compiler says, sheetPropInfo is not a property of NSWindowController. It is a property of SheetClass (which is not the same as NSWindowController; it is a subclass of NSWindowController).
If you know that SheetController is in fact a SheetClass instance, you need to tell the compiler that fact. You must either declare SheetController as a SheetClass or cast it down from an NSWindowController to a SheetClass.

Objective C - Can't set superclass property in subclass

Take this simple class hierarchy:
Tree.h:
#interface Tree : NSObject
#property (nonatomic, assign) id<TreeDelegate> delegate;
#end
Tree.m:
#implementation Tree
#synthesize delegate;
#end
Aspen.h:
#interface Aspen : Tree
- (void)grow:(id<TreeDelegate>)delegate;
#end
Aspen.m:
#implementation Aspen
- (void) grow:(id<TreeDelegate>)d {
self.delegate = d;
}
#end
When I try to do self.delegate = d;, I'm getting the following error:
-[Aspen setDelegate:]: unrecognized selector sent to instance 0x586da00
I was expecting the Tree parent class's delegate property to be visible to the subclass as-is, but it doesn't seem to be since the error indicates the parent class's synthesized setter isn't visible.
What am I missing? Do I have to redeclare the property at the subclass level? I tried adding #dynamic at the top of the implementation of Aspen but that didn't work either. Such a simple concept here, but I've lost an hour searching around trying to find a solution. Out of ideas at this point.
--EDIT--
The above code is just a very stripped-down example to demonstrate the issue I'm seeing.
I just tried your code, supplemented by the protocol, an object implementing it, the necessary import and a main function and on my system it works like a charm:
#import <Foundation/Foundation.h>
#protocol TreeDelegate <NSObject>
#end
#interface MyDelegate : NSObject <TreeDelegate>
#end
#implementation MyDelegate
#end
#interface Tree : NSObject
#property (nonatomic, assign) id<TreeDelegate> delegate;
#end
#interface Aspen : Tree
- (void)grow:(id<TreeDelegate>)delegate;
#end
#implementation Tree
#synthesize delegate;
#end
#implementation Aspen
- (void) grow:(id<TreeDelegate>)d {
self.delegate = d;
}
#end
int main(int argc, char ** argv) {
MyDelegate * d = [[MyDelegate alloc] init];
Aspen * a = [[Aspen alloc] init];
[a grow:d];
return 0;
}
I was finally able to figure this out. My actual code leverages a 3rd party static library that defines the classes Tree and Aspen in my example. I had built a new version of the static library that exposed the Tree delegate given in my example, however I did not properly re-link the library after adding it to my project and as a result the old version was still being accessed at runtime.
Lessons learned: be diligent with steps to import a 3rd party library, and when simple fundamental programming concepts (such as in my example text) aren't working, take a step back and make sure you've dotted i's and crossed t's.

passing data between tabs in iOS

it is my first app that I am trying to do on my own and I have some questions. I want to have 4 tabs, and in the first one named "HomeView" I am parsing JSON data (this is done so far).
But what I want is some of the data that are being parsed to be visible in other tabs (and not have to parse them again).
So parts of my code of HomeView is here:
#import "HomeView.h"
#interface HomeView ()
#end
#implementation HomeView
//other code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//data fetched
parsed_date=[res objectForKey:#"date"];
NSLog(#"Date:%#",parsed_date);
[UIAppDelegate.myArray addObject:parsed_date];
}
and I can see the "parsed_date" being printed out correctly.
So I want this parsed_date to be visible in OtherView.
This is my code but I cannot print it out.
OtherView.m
#import "OtherView.h"
#import "HomeView.h"
#import "AppDelegate.h"
#interface OtherView ()
#end
#implementation OtherView
#synthesize tracks_date;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//preview value of other class
tracks_date = [UIAppDelegate.myArray objectAtIndex:0];
NSLog(#"Dated previed in OtherView: %#", tracks_date);
}
and (null) is being printed out.
added code of app delegate.h
#import <UIKit/UIKit.h>
#define UIAppDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate)
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, strong) NSArray *myArray;
#end
So can you suggest me a sollution?
Add the property to your Application Delegate instead.
When assigning the property do something like:
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
delegate.myProperty = #"My Value";
then, in your different tabs, you can retrieve this property in the same manner:
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *valueInTab = delegate.myProperty;
Uh, when you create a HomeView in your last code segment there, you're creating a new object -- a new instance of the class. It will not contain the data from connectionDidFinishLoading unless that method is executed in that instance of the class.
You basically need to use some sort of persistence mechanism to do what you want, either the AppDelegate or static storage along the lines of a "singleton".
While this may not be the best method of doing this, it is easy and effective.
Save your data in your app delegate and retrieve it from there. You can create a shortcut to your app delegate shared application. Then just access the values there.
AppDelegate.h
#define UIAppDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate)
#property (nonatomic, strong) NSArray *myArray;
TabView1.m
#import "AppDelegate.h"
SomeObject *myObject = [UIAppDelegate.myArray objectAtIndex:0];
Like I said, it might not be the best way to organize your data for your application, this method does work for small amounts of data needing to be shared at the application level. Hope this helps.
this happens because you create an instance of HomeView yourself.
it has simply no connections to anything.
your first example works because it is the created and initialized from your nib.
i think the best way is to use an IBOutlet and then connect both 'Views' in InterfaceBuilder.
#interface OtherView ()
IBOutlet HomeView *homeView;
#end
#implementation OtherView
#synthesize tracks_date;
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Dated previed in OtherView: %#", homeView.parsed_date);
}
- (void)dealloc:
{
[homeView release];
}
have a look here, it will demonstrate it much more
In InterfaceBuilder you can manage your Objects and connect them (via IBOutlets and IBAction, ...) together.
I think this video is a good demonstration how this concept work.

How to pass values between 2 NSWindowController

I am stuck trying to pass data from one NSWindowController to other one.
I have 2 NSWindowController that has already been instanced and their respective NIB been loaded in screen, in fact firstWindowController load first, get some input from user and do some calculation and save them in several variables and IBOutlets. Upon user action (NSButton) in firstWindowController the secondWindowController load the second Nib window.
Let say:
firstWindowController.h
#class secondWindowController;
#interface firstWindowController : NSWindowController
{
secondWindowController *_secondWindowController;
}
#property long double onedata;
#property (strong) IBOutlet NSTextField *rZab;
#property (strong) IBOutlet NSTextField *xZab;
#end
In firstWindowController.m is the code that instance _secondWindowController, do synthesize in all #property's variables and objects and load the associated nib screen. In the same way, onedata variables and both IBOulets get some values assigned. Omitted for simplicity.
secondWindowController.h
#interface secondeWindowController: NSWindowController
long double newdata;
-(void)getDataFromFirstWC;
#end
secondWindowController.m
#import "firstWindowController.h"
#import "secondWindowController.h"
#import "myAppDelegate.h"
#implementation secondWindowController
-(void)getDataFromFirstWC
{
newdata = 0.0;
newdata = (_firstWindowController.onedata);
// Compilation fails here...
}
#end
This do not compile. The instance of _firstWindowController is not recognized ??.
Use of undeclared identifier '_firstWindowController'
The instance of _firstWindowController has been created in my application delegate already and it is responsible to load the first window nib.
Any help to get this done?. Other answers to more o less similar questions have not help me.
You need to have an instance of your firstWindowController in the secondWindowController. Try this:
in your seconWindowController.h:
#class firstWindowController //<-- add this
#interface secondeWindowController: NSWindowController
{
firstWindowController *fwc; //<-- and this
}
long double newdata;
-(void)getDataFromFirstWC;
#end
in your seconWindowController.m:
#import "firstWindowController.h"
#import "secondWindowController.h"
#import "myAppDelegate.h"
#implementation secondWindowController
-(void)getDataFromFirstWC {
newdata = 0.0;
newdata = (fwc.onedata); //<-- add this and it should work
NSLog(#"newdata is: %f", newdata);
}
#end
As long as I understood your code so far you don't need to create an instance of the secondWindowController in your firstWindowController. Good luck!

Getting an error while trying to access property from an extern Controller in Xcode 4.2

In a first controller, I create an instance variable for my model, because I want to edit its content from a controller and then access the same object from another controller.
In the second controller, I get an error when trying to access the object:
Property 'levels' not found on object of type FirstController.
Model.h
#imports....
#property (readwrite,copy) NSMutableString *answersString;
FirstController.h
#import <UIKit/UIKit.h>
#import "Model.h"
#interface FirstController : UIViewController{
// some declarations
}
#property (nonatomic, retain) LevelsCompleted *levels;
#end
FirstController.m
#import "FirstController.h"
#interface FirstController(){
//stuff
}
#end
#implementation FirstController
#synthesize levels;
//stuff
- (IBAction)backButton:(id)sender { // This is the changeAnswerString method
if (levels ==nil) self.levels = [[LevelsCompleted alloc]init];
self.levels.answersString=#"1";
[self dismissModalViewControllerAnimated:NO];
}
#end
SecondController.m
#import "SecondController.h"
#import "FirstController.h"
#interface SecondController(){
//stuff
}
#end
#implementation SecondController
-(void) viewWillAppear:(BOOL)animated{
NSLog(#"%#",FirstController.levels.answersString);
// the line above gives me the error "Property 'levels' not found on object of type FirstController
}
#end
Can someone tell me what I am doing wrong here? I have tried to create a FirstController object in the SecondController.h, but this does not give me the same property and hence I do not get the right value of the NSString I modified in the first view.
levels is a instance variable so you cannot access it without instantiating an object first.
You should do something like
FirstController *controller = [[FirstController alloc] initWithNibName:#"First" bundle:nil];
NSLog(#"%#",controller.levels.answersString);
[controller release]
You cannot access another viewcontroller from current viewcontroller directly. Define Level in AppDelagte method and then you can access it from anywhere.
What about moving/adding the LevelsCompleted *levels property to the secondviewcontroller and fill SecondViewcontroller.levels.answerstring when you use backbutton: in you first controller?
As a advice try NSUSERDEFAULT to access it,.,
By Doing Things As Below you can Achive as You want
Ddeclare NSMutableString As in your viewController Class As Global variable.
1) LevelsCompleted.h Class
#import <UIKit/UIKit.h>
NSMutableString *answersString;// In this way this answersString would accessible through out the Application and No Need to make property & synthesiz answersString .
#interface LevelsCompleted : UIViewController{
}
LevelsCompleted.m Class
//First create that NSMutableString object in its LevelsCompleted.m class
#import"LevelsCompleted.h"
#interface LevelsCompleted
-(void)viewDidLoad{
answersString=[NSMutableString alloc]init];//here created answersString object
}
#end //end of LevelsCompleted
2)FirstController.h class
#import <UIKit/UIKit.h>
extern NSMutableString *answersString;
#interface FirstController : UIViewController{
// some declarations
}
#end
FirstController.m class
#import "FirstController.h"
#implementation FirstController
- (IBAction)backButton:(id)sender {
// Because i have created that answersString Global in LevelsCompleted.h class
//we can directly Access and can set the any string Value to that answersString as Below
answersString=#"1";
[self dismissModalViewControllerAnimated:NO];
}
#end
SecondController.h class
extern NSMutableString *answersString;// please do this carefully fro getting access the answersString instance
#interface SecondController:UIViewController{
//stuff
}
#end
SecondController.m class
#implementation SecondController
-(void) viewWillAppear:(BOOL)animated{
NSLog(#"%#",answersString);//here you may access easily.
}
#end
In above code everything would work because i have done the same thing in my app
just try to catch the concept of extern, global variable .