UIView as dictionary key? - iphone

I want to have a NSDictionary that maps from UIViews to something else.
However, since UIViews do not implement the NSCopying protocol, I can't use them directly as dictionary keys.

You can use an NSValue holding the pointer to the UIView and use this as key. NSValues
are copyable. but, if the view is destroyed, the NSValue will hold a
junk pointer.

Here is the actual code (based on the answer by luvieere and further suggestion by Yar):
// create dictionary
NSMutableDictionary* dict = [NSMutableDictionary new];
// set value
UIView* view = [UILabel new];
dict[[NSValue valueWithNonretainedObject:view]] = #"foo";
// get value
NSString* foo = dict[[NSValue valueWithNonretainedObject:view]];

Although this isn't really what they're intended for, you could whip up a functional dictionary-like interface using Associative References:
static char associate_key;
void setValueForUIView(UIView * view, id val){
objc_setAssociatedObject(view, &associate_key, val, OBJC_ASSOCIATION_RETAIN);
}
id valueForUIView(UIView * view){
return objc_getAssociatedObject(view, &associate_key);
}
You could even wrap this up in a class ThingWhatActsLikeADictionaryButWithKeysThatArentCopyable*; in that case you might want to retain the views that you use as keys.
Something like this (untested):
#import "ThingWhatActsLikeADictionaryButWithKeysThatArentCopyable.h"
#import <objc/runtime.h>
static char associate_key;
#implementation ThingWhatActsLikeADictionaryButWithKeysThatArentCopyable
- (void)setObject: (id)obj forKey: (id)key
{
// Remove association and release key if obj is nil but something was
// previously set
if( !obj ){
if( [self objectForKey:key] ){
objc_setAssociatedObject(key, &associate_key, nil, OBJC_ASSOCIATION_RETAIN);
[key release];
}
return;
}
[key retain];
// retain/release for obj is handled by associated objects functions
objc_setAssociatedObject(key, &associate_key, obj, OBJC_ASSOCIATION_RETAIN);
}
- (id)objectForKey: (id)key
{
return objc_getAssociatedObject(key, &associate_key);
}
#end
*The name may need some work.

Provided you don't need to support before iOS 6, NSMapTable (suggested by neilsbot) works well because it can provide an enumerator over the keys in the collection. That's handy for code common to all of the text fields, like setting the delegate or bi-directionally syncing the text values with an NSUserDefaults instance.
in viewDidLoad
self.userDefFromTextField = [NSMapTable weakToStrongObjectsMapTable];
[self.userDefFromTextField setObject:#"fooUserDefKey" forKey:self.textFieldFoo];
[self.userDefFromTextField setObject:#"barUserDefKey" forKey:self.textFieldBar];
// skipped for clarity: more text fields
NSEnumerator *textFieldEnumerator = [self.userDefFromTextField keyEnumerator];
UITextField *textField;
while (textField = [textFieldEnumerator nextObject]) {
textField.delegate = self;
}
in viewWillAppear:
NSEnumerator *keyEnumerator = [self.userDefFromTextField keyEnumerator];
UITextField *textField;
while (textField = [keyEnumerator nextObject]) {
textField.text = [self.userDefaults stringForKey:[self.textFields objectForKey:textField]];
}
in textField:shouldChangeCharactersInRange:replacementString:
NSString *resultingText = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(resultingText.length == 0) return YES;
NSString *preferenceKey = [self.textFields objectForKey:textField];
if(preferenceKey) [self.userDefaults setString:resultingText forKey:preferenceKey];
return YES;
And now I will go cry, because I implemented all of this before realizing that my iOS 5.1-targeted app can't use it. NSMapTable was introduced in iOS 6.

Rather than store a pointer to the view and risk the garbage issue, just give the UIView a tag and store the tag's value in the dictionary. Much safer.

I'm using a simple solution under ARC provided by Objective-C++.
MyClass.mm:
#import <map>
#implementation MyClass
{
std::map<UIView* __weak, UIColor* __strong> viewMap;
}
- (void) someMethod
{
viewMap[self.someView] = [UIColor redColor];
}
In this example I am getting stronger type checking by making all the values have to be a UIColor* which is all I needed this for. But you could also use id as the value type if you want to allow any object as the value, ex: std::map<UIView* __weak, id __strong> viewMap; Likewise for keys: id __weak, id __strong> viewMap;
You can also vary the __strong and __weak attributes as needed. In my case, the views are already retained by the view controller that I use this in, so I saw no need to take a strong pointer to them.

a simple solution when you just want UIView as key occasionally,I use it to store UILabel and UIColor
NSArray<UIView *> *views = #[viewA,viewB,viewC,viewD];
NSArray *values = #[valueA,valueB,valueC,valueD];
for(int i = 0;i < 4;i++) {
UIView *key = views[i];
id value = values[i]
//do something
}
id value = values[[views indexOfObject:key]]

Related

I want to set an arbitrary key:value property on a UIView

For my iOS program, I want to set an arbitrary key:value property on a UIView. I couldn't find any way to do this. Any ideas?
Layers are key-value compliant, according to https://stackoverflow.com/a/400251/264619 (go upvote that answer), so you could set key:values on a view's layers instead.
UIView *myView = [[UIView alloc] init];
[myView.layer setValue: #"hello" forKey: #"world"];
Attach an NSMutableDictionary to the UIView using objc_setAssociatedObject.
http://developer.apple.com/library/ios/ipad/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocAssociativeReferences.html
A common approach is to use the receiver's memory address as a key in a dictionary, and set
subsequent, embedded ditionaries for those keys:
#define KEY(o) [NSString stringWithFormat:#"%x", o]
- (id) init
{
if ((self = [super init])
{
// other stuff
NSMutableDictionary *globalKeys = [NSMutableDictionary new]; // don't forget to release in dealloc
}
return self;
}
// and where you want to set a key-value pair:
- (void) addKey:(NSString *)key value:(id)value forObject:(id)obj
{
NSString *objKey = KEY(obj);
NSDictionary *objDict = [globalKeys objectForKey:objKey];
if (!objDict)
{
[globalKeys setObject:[NSMutableDictionary dictionary] forKey:objKey];
}
[objDict setValue:value forKey:key];
}
Hope it helps.

When we need Pointer of BOOL Variable in Objective C?

In which case we need a pointer of a BOOL variable in Objective C language?
I have a code for collapsible UITableView in which there is a function declaration:
- (void)toggle:(BOOL*)isExpanded section:(NSInteger)section;
and its definition is:
- (void)toggle:(BOOL*)isExpanded section:(NSInteger)section
{
*isExpanded = !*isExpanded;
NSArray *paths = [self indexPathsInSection:section];
if (!*isExpanded)
{
[self.tableview deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
}
else
{
[self.tableview insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
}
*isExpanded = !*isExpanded; What is the meaning of this statement as I have never used this kind of statement in case of BOOL Variable.
Following are other two functions of same code which are called in the sequence of above function:
- (NSArray*)indexPathsInSection:(NSInteger)section
{
NSMutableArray *paths = [NSMutableArray array];
NSInteger row;
for ( row = 0; row < [self numberOfRowsInSection:section]; row++ )
{
[paths addObject:[NSIndexPath indexPathForRow:row inSection:section]];
}
return [NSArray arrayWithArray:paths];
}
- (NSInteger)numberOfRowsInSection:(NSInteger)section
{
return [[sectionDataArray objectAtIndex:section] count];
}
sectionDataArray is the array for number of rows in each section. I may be unclear but if you got my point please explain all this.
Here is the link to that code
Thanks
Pointers to variables (or pointer to pointers of objects) are useful, if you want to change their value in another function. If you pass a plain BOOL to a method, you can use it, but if you change it, this change is only local as it was passed by value. If you pass the pointer/address of the variable instead, you can also change its real value.
This comes in handy if you need more than one return value and don't want to wrap it up in an object. It's also a common pattern in Cocoa where NSError variables are passed as pointers, i.e -(BOOL) doSomethingError:(NSError **)error.
It's unclear why you did have to pass the pointer to a BOOL. Even if you were tracking the expanded status of all sections using an array of BOOLs, I would guess setting it up as an instance variable would have been better.
*isExpanded = !*isExpanded;
This is basically flipping the value of the BOOL. Since you've passed a pointer, you will be able to see the flip in the caller method.
As such, the second part indulges itself in building a list of all index paths in a particular section so that the app can delete the section using deleteRowsAtIndexPaths:withRowAnimation: method of UITableView. Somehow using deleteSections:withRowAnimation: method could've been easier. Same thing goes for insert.. methods.
An array of booleans
Assuming that you need to maintain a dynamic array of BOOLs. NSMutableArray is a proper fit.
Say, you start off with a certain number of sections that have expanded set to NO.
/* In the interface of the view controller */
NSMutableArray * expandedStatuses;
#property (nonatomic, retain) NSMutableArray * expandedStatuses;
/* In viewDidLoad or viewWillAppear:, as needed */
self.expandedStatuses = [NSMutableArray array];
for ( int i = 0; i < numberOfSections; i++ ) {
[self.expandedStatuses addObject:[NSNumber numberWithBool:NO]];
}
Later, in your toggle:section: method do this,
/* Getting the expanded status of the section */
BOOL expanded = [[self.expandedStatuses objectAtIndex:section] boolValue];
/* Flipping the expanded status of the section */
[self.expandedStatuses replaceObjectAtIndex:section withObject:[NSNumber numberWithBool:!expanded]];
If you are interested in deleting a particular section,
[self.expandedStatuses removeObjectAtIndex:sectionIndexToDelete];
And if you are interested in adding,
/* Adding at the end */
[self.expandedStatuses addObject:[NSNumber numberWithBool:NO]];
/* Or adding it in between */
[self.expandedStatuses insertObject:[NSNumber numberWithBool:NO] atIndex:sectionIndexToInsertAt];
So NSMutableArray is pretty flexible to play with. You can consider it as an option to switch to.
They are intended to use isExpanded even after the exit of toggle: method with the modified value.
*isExpanded = !*isExpanded;
You could avoid using BOOL pointer in method by declaring isExpanded as the member variable (iVar) pf your class .
And use belwo
isExpanded = !isExpanded;
Instead of using
*isExpanded = !*isExpanded;
You can try using
isExpanded[0] = !isExpanded[0];
BOOL is not class type it is
typedef signed char BOOL;
You can not have pointer to BOOL variable.

Problem with allocating memory for an Objective-C data object

I've been programming objective-C for a few months now and have done pretty well so far without having to post any questions. This would be my first. The problem is that I'm getting a memory leak warning from a data object in one of it's methods. I can see that the problem is that I'm sending an alloc to it without releasing it, but I don't know how else to get it to retain the object in memory. If I take the alloc out, the program crashes. If I leave it in, it leaks memory. Here is the method in question:
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
newFeature.featureID = fID;
newFeature.featureName = fName;
newFeature.featureSecure = fSecure;
return [newFeature autorelease];
}
This method is called by another method in my view controller. This method is as follows:
+ (NSMutableArray*) createFeatureArray {
NSString *sqlString = #"select id, name, secure from features";
NSString *file = [[NSBundle mainBundle] pathForResource:#"productname" ofType:#"db"];
sqlite3 *database = NULL;
NSMutableArray *returnArray = [NSMutableArray array];
if(sqlite3_open([file UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = [sqlString UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
Feature *myFeature = [Feature featureWithID:sqlite3_column_int(compiledStatement,0)
name:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]
secure:sqlite3_column_int(compiledStatement,2)];
[returnArray addObject:myFeature];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return returnArray;
}
I have tried several things, such as creating a featureWithFeature class method, which would allow me to alloc init the feature in the calling method, but that crashed the program also.
Please let me know if you need any clarification or any other parts of the code. Thank you in advance for your help.
UPDATE: 4/14/2011
After reading the first two responses I implemented the suggestion and found that the program is now crashing. I am at a complete loss as to how to track down the culprit. Hoping this helps, I am posting the calling method from the view controller as well:
- (void)setUpNavigationButtons {
// get array of features from feature data controller object
NSArray *featureArray = [FeatureController createFeatureArray];
int i = 0;
for (i = 0; i < [featureArray count]; i++) {
Feature *myFeature = [featureArray objectAtIndex:i];
CGRect buttonRect = [self makeFeatureButtonFrame:[featureArray count] withMember:i];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setFrame:buttonRect];
[aButton addTarget:self action:#selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
[aButton setTitle:[NSString stringWithFormat:#"%#",myFeature.featureName] forState:UIControlStateNormal];
aButton.tag = myFeature.featureID;
[self.view addSubview:aButton];
}
}
NOTE: These methods are posted in reverse of the order they are invoked. This last method calls the second method, which in turn, calls the first.
UPDATE: I've updated these functions to show what is in there now: Below, I will post the header files for the object - maybe that will help
#interface Feature : NSObject {
int featureID;
int featureSecure;
NSString *featureName;
}
#property (nonatomic, assign) int featureID;
#property (nonatomic, assign) int featureSecure;
#property (nonatomic, retain) NSString *featureName;
- (id) init;
- (void) dealloc;
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure;
#end
#interface FeatureController : NSObject {
}
- (id) init;
- (void) dealloc;
+ (NSMutableArray*) createFeatureArray;
+ (Feature*) getFeatureWithID:(int)fetchID;
#end
Convenience methods should follow the convention of returning autoreleased objects. Change this:
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
...
return newFeature;
}
to:
+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
...
return [newFeature autorelease];
}
The name of your method - +featureWithID:name:secure: - indicates that it returns an object that the caller does not own. Instead, it is returning an object that has been retained, that the caller therefore owns and must release. To fix this (and your leak), simply replace return newFeature with return [newFeature autorelease].
There's nothing more you need to do, because your own code doesn't need a long-lasting ownership claim, and the array to which you're adding the object will manage its own ownership claim over it.
In +createFeatureArray, you’re over releasing the array:
+ (NSMutableArray*) createFeatureArray {
…
NSMutableArray *returnArray = [[[NSMutableArray alloc] init] autorelease];
…
return [returnArray autorelease];
}
In the first line, you used +alloc, so you own the array. Then you used -autorelease, so you do not own the array any more. This means that you shouldn’t send -release or -autorelease to it, which you are doing in the return line.
You can fix that by changing those lines to:
+ (NSMutableArray*) createFeatureArray {
…
NSMutableArray *returnArray = [NSMutableArray array];
…
return returnArray;
}
Also, unless it is relevant to callers that the array is mutable, you should change that method to return NSArray instead of NSMutableArray. You could keep your code as is, i.e., return a mutable array even though the method declaration states that the return type is NSArray.
As for your convenience constructor, there are essentially two choices depending on whether you want to return an owned or a non-owned object:
if you want to return an owned object, allocate it with +alloc or +new and return it without autoreleasing it. Your method name should contain new, e.g. +newFeatureWithId:…
if you want to return an object that’s not owned by the caller, allocate it with +alloc or new and autorelease it before/upon returning it to the caller. Your method name should not contain new, alloc, or copy.
In -setUpNavigationButtons, you obtain a non-owned array via +createFeatureArray, allocate a mutable array based on it, and release the mutable array without adding or removing elements from it. A mutable array makes sense when you need to add/remove elements. If you don’t have this need, you could change your method to:
- (void)setUpNavigationButtons {
// get array of features from feature data controller object
NSArray *featureArray = [FeatureController createFeatureArray];
…
// [featureArray release];
You’d remove that [featureArray release] since you do not own featureArray inside that method.
Edit: In -setUpNavigationButtons, you’re retaining the button you create and soon after you’re releasing it. In that particular method, those are idempotent operations — they aren’t wrong per se but are not necessary at all. You could replace that code with
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
…
[self.view addSubview:aButton];
// [aButton release];
i.e., do not retain it and do not release it.

NSString function

I get a null return when i try out my NSString function.
//Track.m
static NSString* trackUrl;
//static NSString* getTrackNumberUrl;
#implementation Track
- (NSString*)trackUrl {
return #"http://site.com/?a=";
}
- (NSString*)setTrackNumberUrl:(NSString*)trackNumberUrl {
if (trackUrl != trackNumberUrl) {
return [trackUrl stringByAppendingFormat:trackNumberUrl];
}
return #"Error no trackNumber";
}
- (NSString*)getTrackNumberUrl:(NSString*)trackNumber {
return [[[self alloc] setTrackNumberUrl:trackNumber] autorelease];
}
#end
MainView.m, just to show the return answer in NSlog
- (NSString *) trackNumber{
return [track getTrackNumberUrl:#"86147224549XX"];
}
- (void)drawRect:(CGRect)rect {
NSLog(trackNumber);
}
I get a null return answer? Have i miss something? Thanks.
Edit some in Track.m
- (NSString*)setTrackNumberUrl:(NSString*)trackNumberUrl {
if (trackUrl != trackNumberUrl) {
return [trackUrl stringByAppendingString:trackNumberUrl];
}
return #"Error no trackNumber";
}
- (NSString*)getTrackNumberUrl:(NSString*)trackNumber {
return [[[Track alloc] setTrackNumberUrl:trackNumber] init];
}
This is how it should work.
getTrackNumberUrl --> setTrackNumberUrl --> trackUrl (return) --> setTrackNumberUrl + trackNumber --> getTrackNumberUrl (trackNumberUrl = trackUrl + trackNumber)
I have this code to set reference to Track
#class Track;
#interface MainView : UIView {
Track *track;
}
#property (nonatomic, retain) IBOutlet Track *track;
Well if don't should use self alloc, what should i use?
You have a lot of problems with your code.
return [trackUrl stringByAppendingFormat:trackNumberUrl];
You should not use an arbitrary string as a format, because if it contains a format specifier like "%d" then the method will go looking for a variable that isn't there, and will likely crash. You should use stringByAppendingString: instead. However, that doesn't seem to be what you want here, since the method name is setTrackNumberUrl:. If you want to change the value of the trackUrl variable, you can't call stringByAppendingFormat:; all that does is return a new string and leave the original alone. I think you simply want something like
[trackUrl release];
trackUrl = [trackNumberUrl retain];
Another problem:
return [[[self alloc] setTrackNumberUrl:trackNumber] autorelease];
In this context, self is an instance of Track. An instance won't understand the alloc message, that must be sent to a class. It will return a new instance, to which you should send an init message. So you would do something like [[Track alloc] init].
NSLog(trackNumber);
The first parameter to NSLog is a format string, so for the same reasons as above you shouldn't use a variable, you should do something like this: NSLog(#"%#", trackNumber); That line of code prints the value of the variable, trackNumber. Considering that you have a method named trackNumber just above it, I wonder if what you really want to do is call the method and get the result. In that case, you need to write it as [self trackNumber] which will call the method and return an NSString.
Most probably track is nil in the trackNumber - have you set it to a correct reference to a Track object?
Also, this code
- (NSString*)getTrackNumberUrl:(NSString*)trackNumber {
return [[[self alloc] setTrackNumberUrl:trackNumber] autorelease];
}
is incorrect. Why are you using [self alloc]? You're allocating a new Track object (using a static method on an object reference, not on a class name, which is an error), setting it's track number URL, and returning an autoreleased NSString, but you're leaking the Track object you allocated.
return [trackUrl stringByAppendingFormat:trackNumberUrl];
I'm not sure bout this one,
try using it as a format for string.
return [trackUrl stringByAppendingFormat:#"%#",trackNumberUrl];

Possible View Caching problem?

I'm building an iphone app and I've got a table view with some textfields inside the cells, the content of the fields is set in viewWillAppear (its a grouped TableView w/ 3 fields that are always the same). The content of the text fields is retrieved from getter methods that return values from various class variables.
The problem I'm having is the getter seems to be returning the original value, not the value that is modified by the setter method. The class variable is an NSMutableString. Is it possible the view is caching the method call?
//header file
#implementation ManageWorkoutViewController : UIViewController {
NSMutableString *workoutDifficulty;
}
-(void)setWorkoutDifficulty:(NSString *)value;
-(NSString *)getWorkoutDifficulty;
#end
//implementation file
-(NSString *)getWorkoutDifficulty {
if (nil == workoutDifficulty) {
workoutDifficulty = [NSMutableString stringWithString:#"Easy"];
}
NSLog(#"getter: Returning workoutDifficulty as: %#", workoutDifficulty);
return workoutDifficulty;
} //end getWorkoutDifficulty
-(void)setWorkoutDifficulty:(NSString *)value {
workoutDifficulty = [NSString stringWithFormat:#"%d", value];
NSLog(#"setter: workoutDifficulty set as: %#", workoutDifficulty);
}//end setWorkoutDifficulty
//elsewhere in the implementation another table view is
//pushed onto the nav controller to allow the user to pick
//the difficulty. The initial value comes from the getter
workoutDifficultyController.title = #"Workout Difficulty";
[workoutDifficultyController setOriginalDifficulty:[self getWorkoutDifficulty]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[(UINavigationController *)self.parentViewController pushViewController:workoutDifficultyController
animated:YES];
//then in that workoutDifficultyController it calls back into the first controller to set the selected value:
[manageWorkoutController setWorkoutDifficulty:selectedDifficulty];
You've got many issues here. First, you're creating your accessors incorrectly. The problem that's particularly causing you trouble is this line:
workoutDifficulty = [NSString stringWithFormat:#"%d", value];
value is an NSString here. You should be receiving a warning about this. I believe "Typecheck Calls to printf/scanf" is turned on by default, and should catch this. workoutDifficulty is being set to some random number (probably taken from the first 4 bytes of value).
Here is what you probably meant. I would probably switch workoutDifficulty to an enum, but I'm keeping it an NSString for consistency with your code. I'm also doing this without properties because you did, but I would use a property here.
//header file
#implementation ManageWorkoutViewController : UIViewController {
NSString *_workoutDifficulty;
}
-(void)setWorkoutDifficulty:(NSString *)value;
-(NSString *)workoutDifficulty; // NOTE: Name change. "getWorkoutDifficulty" is incorrect.
#end
//implementation file
-(NSString *)workoutDifficulty {
if (nil == workoutDifficulty) {
_workoutDifficulty = [#"Easy" retain];
}
NSLog(#"getter: Returning workoutDifficulty as: %#", _workoutDifficulty);
return _workoutDifficulty;
} //end workoutDifficulty
-(void)setWorkoutDifficulty:(NSString *)value {
[value retain];
[_workoutDifficulty release];
_workoutDifficulty = value;
NSLog(#"setter: workoutDifficulty set as: %#", _workoutDifficulty);
}//end setWorkoutDifficulty
You have to retain workoutDifficulty whenever you set it to a new value (and release the old value).