Unable to access "center" property of UIView from outside the class - objective-c

I have an instance of UICollectionViewCell ( lets call it c ).
c has a property child of type B*
#property (strong) B* child;
in B there is a declaration
#property (strong) C* parent;
in C.m I set
self.child.parent = self
In B.m I have code :
position = self.parent.center.x;
For some reason I can not access center property of UIVIew from outside the instance. Is it private ? I looked in UIView.h and in the documentation. I dont see it being private.
Accessing self.parent in B.m is giving me the correct values ...
So why cant I access it ? In C.m
self.center
is working as expected ...
EDIT : With the real code
This is the so-called "C.h"
#import <UIKit/UIKit.h>
#import "UIMovableImage.h"
#interface LetterCollectionCell : UICollectionViewCell
#property (weak, nonatomic) IBOutlet UIImageView *letterCellView;
#end
This is "B.h"
#import <UIKit/UIKit.h>
#class LetterCollectionCell;
#interface UIMovableImage : UIImageView
{
CGPoint currentPoint;
}
#property (strong) LetterCollectionCell* parent;
#end
This is "C.m"
#import "LetterCollectionCell.h"
#import "LettersCollection.h"
#implementation LetterCollectionCell
-(void)PrepareImage:(int)index Hint:(BOOL)hint Rotate:(BOOL)rotate
{
if ([_letterCellView respondsToSelector:#selector(parent)])
{
UIMovableImage* temp = ((UIMovableImage*)self.letterCellView);
temp.parent = self;
}
}
#end
And here is the "B.m"
#import "UIMovableImage.h"
#import "LetterCollectionCell.h"
#implementation UIMovableImage
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Get active location upon move
CGPoint activePoint = [[touches anyObject] locationInView:self.parent];
// Determine new point based on where the touch is now located
CGPoint newPoint = CGPointMake(self.parent.center.x + (activePoint.x - currentPoint.x),
self.parent.center.y + (activePoint.y - currentPoint.y));
}
#end
Please note that the LetterCollectionCell's letterCellView is of type UIImageView and not of type UIMovableImage. The reason is that I want to keep this declaration as a placeholder. In the Interface Builder I have two scenes where the LetteCollection is used. In one scene I set the imageview to be of UIMovableImage ( thru Inspector Window ) and at the other I left the image to be of type UIImageView. So the run-time will create the proper class upon different scenes and at the collection I check : if the image has a property "parent" - I set it up. Otherwise I dont.
It works fine, the assignment works just fine.... but the access is not

The only reason you wouldn't have access to the property would be that the class is not aware of it (forward declaration). Therefore, you must have a missing #import "C.h" in B's implementation file.
Perhaps an example is necessary to appease the downvoter, so let's use yours:
Here's what B's header should look like
//Give us the ability to subclass UICollectionViewCell without issue
#import <UIKit/UIKit.h>
//forward declare a reference to class B. We cannot access it's properties until we
//formally import it's header, which should be done in the .m whenever possible.
#class B;
#interface C : UICollectionViewCell
//Declare a child property with a strong reference because we are it's owner and creator.
#property (strong, nonatomic) B* child;
#end
Now C's header.
//import foundation so we can subclass NSObject without a problem.
#import <Foundation/Foundation.h>
//Forward-declare classe C so we don't have to #import it here
#class C;
#interface B : NSObject
//keep an unretained reference to our parent because if the parent and the child have
//strong references to each other, they will create a retain cycle.
#property (unsafe_unretained, nonatomic) C* parent;
#end
Now that that's out of the way, here's the implementation of C that you are most likely using:
#import "C.h"
#import "B.h"
#implementation C
-(id)init {
if (self = [super init]) {
self.child = [[B alloc]init];
self.child.parent = self;
}
return self;
}
#end
Not too bad, but here's the problem:
#import "B.h"
#implementation B
-(id)init {
if (self = [super init]) {
CGFloat position = self.parent.center.x; //ERROR!
}
return self;
}
#end
because C's only declaration that it has a center property (or rather that it's superclass has a center property), and C's type are in the C.h file, B has no knowledge of C's properties without an explicit #import of C.h.

I found the reason.
The whole question was barking at the wrong tree.
In fact, the bug was at the other place and I just kept looking at the "Invalid Expression" int the debugger's watch window.
To sum up : accessing the "center" property worked just find under the circumstances described in the original question. The "Invalid Expression" of the debugger and a bug in a different place made me chase a wrong thing.
I +1d the generally correct answers and comments but can not accept them since it may mislead people.
Thanks to all for the help and the effort

According to the sequence of your question it seems to me that you start with setting the C.m but on that line code the child instance is not set yet.. that self.child = nil so setting self.child.parent = self will give you no result... Accordingly on B.m will not have the access to the parent object...
if i am correct just set your child instance object -- self.child = B* --- before set self.child.parent = self......

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.

Access ivar from subclass in Objective-C

I have class A which has this declaration in it's .m file:
#implementation A {
NSObject *trickyObject;
}
And class B which has this declaration in it's .h file:
#interface B : A
#end
Is there any possibility to access the trickyObject from a method declared in the class B?
If you have a property or method that is private, but you want to make accessible to subclasses, you can put the declaration in a category.
So consider A:
// A.h
#import Foundation;
#interface A : NSObject
// no properties exposed
#end
And
// A.m
#import "A.h"
// private extension to synthesize this property
#interface A ()
#property (nonatomic) NSInteger hiddenValue;
#end
// the implementation might initialize this property
#implementation A
- (id)init {
self = [super init];
if (self) {
_hiddenValue = 42;
}
return self;
}
#end
Then consider this category:
// A+Protected.h
#interface A (Protected)
#property (readonly, nonatomic) NSInteger hiddenValue;
#end
Note, this extension doesn’t synthesize the hiddenValue (the private extension in A does that). But this provides a mechanism for anyone who imports A+Protected.h to have access to this property. Now, in this example, while hiddenValue is really readwrite (as defined in the private extension within A), this category is exposing only the getter. (You obviously could omit readonly if you wanted it to expose both the getter and the setter, but I use this for illustrative purposes.)
Anyway, B can now do things like:
// B.h
#import "A.h"
#interface B : A
- (void)experiment;
// but again, no properties exposed
#end
And
// B.m
#import "B.h"
#import "A+Protected.h"
#implementation B
// but with this category, B now has read access to this `hiddenValue`
- (void)experiment {
NSLog(#"%ld", (long)self.hiddenValue);
}
#end
Now A isn’t exposing hiddenValue, but any code that uses this A (Protected) category (in this case, just B) can now access this property.
And so now you can call B methods that might be using the hiddenValue from A, while never exposing it in the public interfaces.
// ViewController.m
#import "ViewController.h"
#import "B.h"
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
B *b = [[B alloc] init];
[b experiment]; // this calls `B`’s exposed method, and that method is using the property not exposed by `A.h`
}
#end
If you’re interested in a real-world example of this, consider UIKit’s:
#import UIKit.UIGestureRecognizerSubclass;
Generally the state of a UIGestureRecognizer is readonly, but this UIGestureRecognizer (UIGestureRecognizerProtected) category exposes the readwrite accessors for state (to be used, as the name suggests, by gesture recognizer subclasses only).

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.

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!

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

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.