Why is my NSDictionary not initializing my specific keys and values when in my model, but works within my controller? - objective-c

In this example my NSDictionary initializes with 0 key/value pairs, as shown in my debugger. It will initialize properly when I do the exact same thing in my ViewController but I would much prefer to stick to MVC design and have the NSDictionary in my model.
ShakespeareViewController.h
#import <UIKit/UIKit.h>
#interface ShakespeareViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *sonnetDisplay;
#end
ShakespeareViewController.m
#import "ShakespeareViewController.h"
#import "ShakespeareModel.h"
#interface ShakespeareViewController ()
#property (nonatomic, strong) ShakespeareModel *sonnet;
#end
#implementation ShakespeareViewController
#synthesize sonnetDisplay = _sonnetDisplay;
#synthesize sonnet = _sonnet;
- (IBAction)sonnetButton:(UIButton *)sender
{
self.sonnetDisplay.text = [self.sonnet grabSonnet:#"19"];
}
#end
ShakespeareModel.h
#import <Foundation/Foundation.h>
#interface ShakespeareModel : NSObject
-(NSString *)grabSonnet:(NSString *)atNumber;
#end
ShakespeareModel.m
#import "ShakespeareModel.h"
#interface ShakespeareModel()
#property (nonatomic, strong) NSDictionary *sonnets;
#end
#implementation ShakespeareModel
#synthesize sonnets = _sonnets;
-(NSDictionary *)sonnets
{
if (!_sonnets)
{
_sonnets = [[NSDictionary alloc] initWithObjectsAndKeys:#"19", #"19", nil];
}
return _sonnets;
}
-(NSString *)grabSonnet:(NSString *)atNumber
{
NSString *chosenSonnet = [self.sonnets objectForKey:#"19"];
return chosenSonnet;
}
#end
Any ideas on what I am doing wrong are greatly appreciated. I can't see why this wouldn't initialize with the object 19 at key value 19.

I don't see any place where you set the view controller's sonnet property to an instance of ShakespeareModel -- so when you call grabSonnet: you're sending a message to nil (and thus getting nothing back.
You should put self.sonnet = [[ShakespeareModel alloc] init] in your view controller some time before you call grabSonnet:... probably in the initializer or in -viewDidLoad.

Related

Set text in the textfield does not work in Obj-C

I would like to set an text in the text field in another class and get it from another class. This is something what I want, but it does not work. Can you please help me. Thank you!
aaa.h
#import <Cocoa/Cocoa.h>
#interface aaa : NSImageView {
IBOutlet NSTextField *message;
}
#property (nonatomic, retain) IBOutlet NSTextField *message;
#end
aaa.m
#import "aaa.h"
#import "bbb.h"
#implementation aaa
#synthesize message;
- (void)awakeFromNib {
// [message setStringValue:#"ok, this works!"]; //but i don't want it from here
[self hello];
}
#end
bbb.h
#import <Foundation/Foundation.h>
#interface NSObject (bbb)
- (void)hello;
#end
bbb.m
#import "bbb.h"
#import "aaa.h"
#implementation NSObject (bbb)
- (void)hello {
aaa *obj = [[[aaa alloc] init] autorelease];
[obj.message setStringValue:#"This doesn't work :("]; // set text here, dont work.
NSLog(#"TEST: %#", [obj.message stringValue]);
}
#end
You are using category, so first thing it is used for extending the functionality of existing class. So you cannot set textfield value inside category. But else you can add some functonality after extracting the value. So you have to pass the value inside the category first. Try like this below:
- (void)awakeFromNib {
NSString *resultString=[self hello:#"This doesn't work :("];
[message setStringValue:resultString];
}
#end
#interface NSObject (bbb)
- (NSString*)hello:(NSString*)yourString;
#end
#implementation NSObject (bbb)
- (NSString*)hello:(NSString*)yourString {
return yourString;
}
#end

Obtaining the string value from separate window to be used on another. Objective C

I have a window with a large NSTextFeildCell, where text can be modified. Upon clicking a button another window appears where the text from the original window can be used some how. The issue I am having is when I attempt to retrieve that text the log spits out...
" -[NSTextView stringValue]: unrecognized selector sent to instance 0x100151860"
Fallowed by a long trace...
I have tried to solve this several different ways but with no luck.
currently,
First window controller
.h
#import <Cocoa/Cocoa.h>
#class NextWindowController;
#interface TextViewWindowController : NSWindowController
#property (nonatomic, weak) NextWindowController *NextWindow;
#property (nonatomic, weak) IBOutlet NSTextFieldCell *txtTextView;
- (IBAction)btnClicked:(id)sender;
- (NSString*)getText;
#end
.m
#import "TextViewWindowController.h"
#import "NextWindowController.h"
#implementation TextViewWindowController
#synthesize NextWindow;
- (IBAction)btnClicked:(id)sender{
[NextWindow setCallingWindow:self];
[NextWindow showWindow:self];
}
- (NSString*)getText{
return [_txtTextView stringValue];// there is a problem with the view...
}
#end
Next Window controller
.h
#import <Cocoa/Cocoa.h>
#class TextViewWindowController;
#interface NextWindowController : NSWindowController{
NSMutableString* str;
}
#property (nonatomic, weak) TextViewWindowController *callingWindow;
#end
.m
#import "NextWindowController.h"
#import "TextViewWindowController.h"
#implementation NextWindowController
#synthesize callingWindow;
- (IBAction)btnEnterClicked:(id)sender{
[str setString:callingWindow.txtTextView.stringValue];
}
- (id)initWithWindow:(NSWindow *)window{
self = [super initWithWindow:window];
if (self) {
str = [[NSMutableString alloc] init];
}
return self;
}
#end
I have also tried str = [callingWindow getText] with the same result.
Any help would be very appreciated!
It's not super intuitive to figure out from Apple's documentation, but to get the raw string value of a NSTextView (which inherits from NSText), just use:
[_txtTextView string];
And since you're using properties, it might be smarter to use the accessor in your function, like this:
- (NSString*)getText{
return [self.txtTextView string];
}

xCode 4.6 Object alloc and init

I'm new to xCode. I'm using xCode 4.6 and I don't understand how xcode instantiates objects fully.
I thought that if you declare the object as a property in the .h file it automatically alloc and init it. the only way I could get my code to work is to do the alloc and init on the property file. I included my sample code below, but can anyone tell me if this is the right way to do this?
#import <Foundation/Foundation.h>
#interface Person : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic) int age;
#end
#import "Person.h"
#implementation Person
#end
#import <UIKit/UIKit.h>
#import "Person.h"
#interface ViewController : UIViewController
#property (strong, nonatomic) Person *person;
#property (weak, nonatomic) IBOutlet UILabel *lblDisplay;
- (IBAction)btnChangeLabel:(id)sender;
#end
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_person = [[Person alloc]init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnChangeLabel:(id)sender {
[_person setName:#"Rich"];
[_person setAge:50];
_lblDisplay.text = [NSString stringWithFormat:#"%# is %d years old.",_person.name,_person.age];
}
#end
You're doing the right thing, except in your btnChangeLabel method, refer to your properties via:
self.person.name = #"Rich";
self.person.age = 50;
_lblDisplay.text = [NSString stringWithFormat:#"%# is %d years old.",self.person.name,self.person.age];
The only time you want to use the underlying variables "_person" is when you need to allocate the space for them. The rest of the time, you'll use their accessors (getters and setters; which is what the "self.person.name =" thing is doing). This way the compiler will know to do ARC-style releases and retains automagically.

My own method isn't being found by the compiler

I recently started learning Objective-C and Cocos-2D. I tried to define my own method for automating the creation of sprites.
I added my own class where I'll create other automation methods as well. Anyhow my .h file looks like this:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#interface ActionsClass : CCNode {
}
#property (nonatomic, strong) CCSprite* createSprite;
#property (nonatomic, strong) CCSprite* spriteName;
#property (nonatomic, strong) NSString* pngName;
#property (nonatomic) CGPoint* spriteCoordinate;
- (CCSprite *)createSprite: (CCSprite *)spriteName: (NSString *)pngName: (CGPoint *)spriteCoordinate;
#end
And the .m is:
#import "ActionsClass.h"
#implementation ActionsClass
#synthesize createSprite = _createSprite;
#synthesize spriteName = _spriteName;
#synthesize pngName = _pngName;
#synthesize spriteCoordinate = _spriteCoordinate;
- (CCSprite *)createSprite: (CCSprite *)spriteName: (NSString *)pngName: (CGPoint *)spriteCoordinate
{
if (!_createSprite)
{
_createSprite = [[CCSprite alloc] init];
_spriteName = [CCSprite spriteWithFile:_pngName];
_spriteName.position = ccp(_spriteCoordinate->x, _spriteCoordinate->y);
[self addChild:_spriteName];
}
return _createSprite;
}
#end
In the main .m file where I want to call the method:
[self createSprite: saif: #"saif.png": ccp(100,100)];
This would give the warning that xcode didn't find the instance method createSprite and defaults it to id
Thanks a lot and sorry if the font or the formatting of the question aren't super neat.
Your method declaration is wrong, so you wont be able to call it.
It should be:
- (CCSprite *)createSprite:(CCSprite *)spriteName pngName:(NSString *)pngName coord:(CGPoint *)spriteCoordinate;
And called like:
[self createSprite:someSprite pngName:somePNGName coord:someCoord];
Edit: I didn't see that you were trying to call this from another class. To do that you will need to import the ActionsClass header file, and call this method on an instance of ActionsClass, e.g.
ActionsClass *actionsClassObject = [[ActionsClass alloc] init];
[actionsClassObject createSprite:someSprite pngName:somePNGName coord:someCoord];

Setting variables in a different class in Cocoa

I'm trying to learn how to set variables for different classes using one main data class.
Here's a diagram of of what I would like to do and the code from my project:
ClassA
#import <Foundation/Foundation.h>
#interface ClassA : NSObject {
NSString *stringA;
NSString *stringB;
}
#property (nonatomic, copy) NSString *stringA;
#property (nonatomic, copy) NSString *stringB;
#property (weak) IBOutlet NSTextField *textA;
#property (weak) IBOutlet NSTextField *textB;
- (IBAction)displayStrings:(id)sender;
#end
#import "ClassA.h"
#implementation ClassA
#synthesize stringA, stringB, textA, textB;
- (IBAction)displayStrings:(id)sender {
[textA setStringValue:stringA];
[textB setStringValue:stringB];
}
#end
Class X
#import <Foundation/Foundation.h>
#interface ClassX : NSObject {
NSMutableString *stringX;
}
- (void)theVariables:(id)sender;
#end
#import "ClassX.h"
#import "ClassA.h"
#implementation ClassX
- (void)awakeFromNib {
[self theVariables:self];
}
- (void)theVariables:(id)sender {
stringX = [[NSMutableString alloc] init];
ClassA *clssA = [[ClassA alloc] init];
[stringX setString:#"stringX for stringA"];
[clssA setStringA:stringX];
[stringX setString:#"stringX for stringB"];
[clssA setStringB:stringX];
}
#end
No errors show up in the code, but when I run the program I am receiving an error about "Invalid parameter not satisfying: aString". It looks like the setStringValue for the IBOutlet is not working. Any suggestions?
I'm not seeing the error you mention, but as far as I can tell from your code, the main problem is this line:
ClassA *clssA = [[ClassA alloc] init];
You must have an instance of ClassA in your xib, which is connected to text fields and a button. That object in the xib is a real object, and if you just create another instance of ClassA somewhere in your code, you have an entirely different object that has no connection to the one that's in your xib.
You need to make sure of/change two things. First, there needs to be an instance of ClassX in your xib. Second, ClassX needs an outlet to a ClassA instance:
#class ClassA; // Declare ClassA so you can use it below
#interface ClassX : NSObject
#property (weak) IBOutlet ClassA * theClassAInstance;
- (void)theVariables:(id)sender;
#end
Which should then be connected in the xib file. Then, in theVariables:, you just use that outlet instead of creating a new instance of ClassA: [[self theClassAInstance] setStringA:#"stringX for stringA"];
Three points of style:
First, you should be importing Cocoa.h: #import <Cocoa/Cocoa.h> instead of Foundation.h in any class that touches the GUI (ClassA in this case). That's where stuff like NSTextField is defined. It works anyways because Cocoa.h is imported via your .pch file, but it's best to be explicit.
Second, creating a mutable string and changing its value to two different literal strings doesn't make a whole lot of sense. Just use the literals directly: [clssA setStringA:#"stringX for stringA"];
Third, You don't need to declare the instance variables separately; #synthesize creates them for you, and it is now the recommended practice to not declare them:
#interface ClassA : NSObject
#property (nonatomic, copy) NSString *stringA;
#property (nonatomic, copy) NSString *stringB;
#property (weak) IBOutlet NSTextField *textA;
#property (weak) IBOutlet NSTextField *textB;
- (IBAction)displayStrings:(id)sender;
#end
Last (four points!), you should really be accessing the values of stringA and stringB in ClassA via the property: [textA setStringValue:[self stringA]];