Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am trying to call BOOL in +(void) method but I can't. Why it would not set in +(void) method? While it is working on all -(void) methods.
.h
#property (nonatomic, assign) BOOL line;
.m
+ (void)normalizeCell:(UITableViewCell *)cell withLables:(NSArray *)lbls sx:(CGFloat)sx widths:(NSArray *)widths
if (![cell.contentView viewWithTag:22])
{
UIImageView *gb = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"table.png"]];
gb = 22;
[cell.contentView addSubview:gb];
[gb release];
}
You can't use your header property in class method (+), only in instance method (-).
This is some kind of static method known from other programming language. In objective-c you can use class method to do some operation which fit to class you've created, but you have to remember that using a class method is NOT an object operation. You don't have to creating objects to use class method and of course you can't access properties of the objects.
+ methods are class level methods and properties are instance level variables. Therefor it's not possible to set them, on what instance would they be set? Class level methods should not be used if you need to keep state. You can keep state if you really want to like this.
+ (BOOL)myBool:(NSNumber *)boolValue{
static BOOL myBool = false;
if (boolValue){
myBool = [boolValue boolValue];
}
return myBool;
}
If you want this to not be part of the public interface just put this directly in the .m file so it's invisible for other classes. Then when you are inside your other class method you can do.
BOOL b = [self myBool:nil]; // get value
[self myBool:[NSNumber numberWithBool:YES]]; // set value
If you for reason would like to access this from your instances you can like this.
BOOL b = [MyClass myBool:nil];
[MyClass myBool:[NSNumber numberWithBool:NO]];
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am quite new in iOS programming but I need it to test out a prototype.
I am receiving a value over bluetooth, which changes when a button is pressed on the physical prototype.
In my app a action has to follow when the button is pressed, therefore I need to know when the value has changed.
I have tried everything I could think of and looked everywhere but found no solution.
This is my current code:
-(void)bean:(PTDBean *)bean didUpdateScratchNumber:(NSNumber *)number withValue:(NSData *)data{
int value = *(int*)([data bytes]);
NSString *lastvalue = nil;
NSString *newValue = [NSString stringWithFormat:#"%d", value];
NSLog(#"ScratchWaarde: %d", value);
if ([newValue isEqualToString:lastvalue]) {
NSLog(#"Last Value: %#", lastvalue);
}else{
NSLog(#"Pushed");
lastvalue = newValue;
}
}
Thank you for helping!
Yeah, it looks like the OP expects lastValue to be kept as state on the object, so...
// in this class's interface
#property(strong,nonatomic) NSString *lastValue;
-(void)bean:(PTDBean *)bean didUpdateScratchNumber:(NSNumber *)number withValue:(NSData *)data{
// it looks like the OP is trying to get a string from the data, so...
NSString *newValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ScratchWaarde: %d", value);
if ([newValue isEqualToString:self.lastvalue]) {
NSLog(#"Last Value: %#", self.lastvalue);
} else {
NSLog(#"Pushed");
self.lastvalue = newValue;
}
}
You code makes no sense. You are saying:
NSString *lastvalue = nil;
NSString *newValue = // ...
if ([newValue isEqualToString:lastvalue]) {
Under no circumstances will newValue ever be equal to lastValue, because lastValue is guaranteed to be nil, because that is the value you are setting it to in the first line (and newValue, because you are setting it to an actual NSString, is guaranteed not to be nil).
So, while I'm not clear on what exactly you are trying to accomplish, this obviously isn't it. It's not so much a programming matter as a matter of simple logical thought. The program can only do what you tell it to do, and what you are telling it to do is silly.
(In all probability what you are not grasping is that lastvalue is purely local to this method, so it is new every time your method is called. If you want a persistent lastvalue, you need a property global to the class, not a local variable.)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to store the title of a view into an NSString but within a class method from one view to be used in another view but I just can't access the title. My code is this:
First view:
+(NSString*)title
{
NSString * strTitle = self.title;
return strTitle;
}
So, anyone could help me??
Thanks!!! . . .
You cant access an instance variable from a class method. So you have to change your method as an instance method
-(NSString*)title {
NSString *strTitle = self.title;
return strTitle;
}
Also make sure you set the title for this another viewcontroller before calling this method.
If you want to pass this data to another UIView class , then you have to make a title property for this UIView class. After initializing the object for this UIView, you can set this title property through this object.
You can set your view's title to viewTitle and get from it.
static NSString * viewTitle = nil ;
+ (NSString *)title {
return viewTitle ;
}
Code to use in secondviewcontroller:
#interface SecondViewController ()
#property(nonatomic,strong) NSString *titleString;
#end
#implementation ViewController
#synthesize titleString;
Code to use in firstviewcontroller:
SecondViewController * controllerObj =[[SecondViewController alloc]init];
controllerObj.titleString=NSStringFromClass([self class]);
[self.navigationController pushViewController:controllerObj animated:YES];
They are not possible for find name of .xib file name.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to find a way to make an object which stores patient information "global" to my application in objective c. Example, class A creates the object, (its basically a user name/ password screen). When they close out the application, I would like the appdelegate's applicationdidEnterBackground to read information from this object(which was created in Class A).
You have a few options:
Make your object a property on your App Delegate
Make it a singleton
One of the options is to create a singleton: https://developer.apple.com/library/mac/documentation/general/conceptual/devpedia-cocoacore/Singleton.html
You can also simply write that data inside NSUserDefaults or to a file, a read it afterwards - if you are using this only occasionally it's better idea.
Make this as a public property of your view and read it from appdelegate - however this is not best option if you later change the view to be a subview or you also lose this object when you gets deallocated.
singleton is the way:
you can make class as UserdataSingleton which overrides NSObject. which you can use all over your application to share data globally (for your case array). this code template may help you:
#import <Foundation/Foundation.h>
#interface UserDataSingleton : NSObject
{
#private
NSArray *globalArray;
}
+(UserDataSingleton *) getInstance;
-(void)saveInUserDatasingletonWithArray:(NSArray *)array;
-(NSDictionary *)getGlobalArray;
#end
and implementation file will be some thing like:
#import "UserDataSingleton.h"
#implementation UserDataSingleton
static UserDataSingleton *userDataSingletonInstance;
+(UserDataSingleton *) getInstance
{
if (userDataSingletonInstance == nil) {
userDataSingletonInstance = [[UserDataSingleton alloc] init];
}
return userDataSingletonInstance;
}
-(void)saveInUserDatasingletonWithArray:(NSArray *)array
{
globalArray = array;
}
-(NSDictionary *)getGlobalDictionary
{
return globalArray;
}
#end
usage:
#import "UserDataSingleton.h"
define USERDATASINGLETON (UserDataSingleton *)[UserDataSingleton getInstance]
......................your code...
NSArray *this_IS_Array_Populated_here_For_Global_Access = [NSArray alloc] initWith....];
[USERDATASINGLETON saveInUserDatasingletonWithArray:this_IS_Array_Populated_here_For_Global_Access];//you put your array for global access.
later some where in any other view or view controller you can get that global array for example lets say you have YourViewController class:
NSMutableArray *yourArrayFromWebResponse = [USERDATASINGLETON getGlobalArray];
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
NSString *firstName2 = #"foo";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:firstName2, #"storeData", nil];
NSString * __strong *storeData = NULL;
storeData = &[dict objectForKey:#"storeData"];
*storeData = #"bar";
When setting storeData, I want that firstName will be changed as well.
I get a build error: "address expression must be an lvalue or a function designator"
How should I do it?
EDIT
In the big picture, I'm trying to create a subclass of UITextField that gets a reference to a variable and sets it in the textField:DidEndEditing method.
That code doesn't make sense and C (Objective-C) doesn't work that way.
The return value of a method is generally in a register and, thus, has no address. Even if it did, getting pointers to the innards of objects so you can muck with them directly is a really bad design pattern.
I don't think you need to subclass UITextField to accomplish your goal. In any case, the solution you are trying to implement has a philosophical flaw because it breaks encapsulation.
How to solve? Your text fields are almost certainly owned by a view controller subclass. So long as that object conforms to the UITextFieldDelegate protocol and each of the text fields has the controller object as its delegate, you should be good. The only task remaining, then, is to map the text fields to a property on your controller or other object.
Let's assume for a second that your controller owns an instance of some data object whose properties you are trying to set with the controller's UI. We'll call it MyDataObject:
#interface MyDataObject : NSObject
#property (nonatomic, strong) NSString *firstName;
#property (nonatomic, strong) NSString *lastName;
#end
#implementation MyDataObject
#end
To map the text fields to the properties on this object, you could do something like:
- (NSString *)propertyNameForTextField:(UITextField *)field {
static NSDictionary *map;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
map = #{(id)self.fnField: #"firstName",
(id)self.lnField : #"lastName" };
});
return map[field];
}
Then in our UITextFieldDelegate method, we do:
- (void)textFieldDidEndEditing:(UITextField *)textField {
[_dataObject setValue:textField.text forKey:[self propertyNameForTextField:textField]];
}
Note that I'm doing no error checking, validation, etc. etc. This is just to show one way of mapping UI elements to properties they should affect. This is on iOS; on Mac OS bindings are available for this use-case.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
First off, I am using the game engine LevelHelper.
Does anyone know the proper way to access an instanced LevelHelper helper class from another class?
For example:
I have my main gameLayer class and a hudLayer class. The hudLayer class is being imported and instanced in the gameLayer class. However i need to be able to access and manipulate the sprites that are loaded in the hudLayer class with gameLayer class.
I was recommended to use the LevelHelper helper instance method. So i create the instance method inside of my hudLayer class, and then call it inside of my init method to load the sprites. I tried using this method as an instance method and i get an error saying unrecognized selector
+[hudLayer hudLoader];
If i try using the method as a class method i get an EXC_BAD_ACCESS Error.
I cant seem to find a solution.
My code:
hudLayer.h :
+(LevelHelperLoader*)hudLoader;
hudLayer.mm :
+(LevelHelperLoader*)hudLoader
{
LevelHelperLoader* lh;
finishScreen = [lh spriteWithUniqueName:#"finishScreen"];
return lh;
}
gameLayer.h :
LHSprite* finishScreen;
gameLayer.mm :
#import hudLayer.h
-(id) init {
[self retrieveRequiredObjects];
}
-(void) retrieveRequiredObjects {
finishScreen = [[hudLayer hudLoader] spriteWithUniqueName:#"finishScreen"];
NSAssert(finishScreen!=nil, #"Couldn't find the menu!");
}
Note: This code is just to make sure my logic and implementation of this is correct.
Any help is appreciated, thanks.
Have you tried stepping through your code in the debugger to find exactly which line causes the crash?
To me it looks as if it is here:
LevelHelperLoader* lh;
finishScreen = [lh spriteWithUniqueName:#"finishScreen"];
You have declared 1h, but you haven't created it. So you are sending a message to a non-existent object.
At very least, something like
LevelHelperLoader* lh = [[LevelHelperLoader alloc] init];
would help.
A cursory glance at the documentation adds more detail:
LevelHelperLoader* loader = [[LevelHelperLoader alloc] initWithContentOfFile:#"level1"];
In the docs, this is an instance variable - which suggests that hudLoader should be an instance method, not a class method:
- (LevelHelperLoader*) hudLoader;
and you should create your LevelHelperLoader* instance in your hudLoader initialiser.
update
You say in your comment:
inside of my init method for hudLayer.mm i call
lh = [[LevelHelperLoader alloc] initWithContentOfFile:#"level1"];
and in the .h i have
LevelHelperLoader* lh;
I am not sure if this is modifications since reading my answer or not. However here are some more thoughts.
Firstly can you sort out your naming conventions. Classes should start with Capitals.
HudLayer.h
Let's declare this lh instance variable as a property in your #interface and improve it's name:
#property (strong) LevelHelperLoader* levelHelper
HudLayer.mm
Allow it to be auto-synthesized or synthesize in your #implementation as:
#synthesize levelHelper = _levelHelper;
Then in your init method
_levelHelper = [[LevelHelperLoader alloc] initWithContentOfFile:#"level1"];
and hudLoader becomes
-(LevelHelperLoader*)hudLoader
{
finishScreen = [self.levelHelper spriteWithUniqueName:#"finishScreen"];
return self.levelHelper;
}
but then ask yourself, what is -hudLoader actually doing? The line that assigns to finishscreen? Is finishscreen an iVar? Do you need it? Perhaps not. Aside from that, all -hudLoader is doing is returning your already-created instance of LevelHelperLoader. Now that your iVar is a property you can access this from gameLayer using dot-notation property syntax, and remove hudLoader altogether:
GameLayer.h
#interface
#property (strong) Hudlayer* hudLayer;
#end
GameLayer.m
-(id) init {
_hudLayer = [[Hudlayer alloc] init];
[self retrieveRequiredObjects];
}
-(void) retrieveRequiredObjects {
finishScreen = [self.hudLayer.levelHelper spriteWithUniqueName:#"finishScreen"];
NSAssert(finishScreen!=nil, #"Couldn't find the menu!");
}
This makes me wonder whether you need a hudLayer class at all (maybe it is doing other useful work)... it looks as if you can get at your levelHelper directly from gameLayer.
GameLayer.h
#interface
#property (strong) LevelHelperLoader* levelHelper;
#end
GameLayer.m
-(id) init {
_levelHelper = [[LevelHelperLoader alloc] initWithContentOfFile:#"level1"];
[self retrieveRequiredObjects];
}
-(void) retrieveRequiredObjects {
finishScreen = [self.levelHelper spriteWithUniqueName:#"finishScreen"];
NSAssert(finishScreen!=nil, #"Couldn't find the menu!");
}
To conclude, I am not suggesting you follow this code line-for-line because I have no idea the broader context of your project. But you do need to sort out your confusion between classes and instances, allocation, instantiation, local vs instance variables. Please take care with naming conventions so that you know when you are sending a message to a Class or an instance of that class, and you know when you are addressing an iVar _directly or via a #property (eg self.property). Be consistent. And think about what a class is actually doing for you.