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.
Related
What is the proper way to add objects in NSMutableArray which is strongly defined by property.
[tapBlockView setTapBlock:^(UIImage* image) {
[self.myImageArray addObject:image]; // self retain cycle
}
If I will create weak reference something like
__weak NSMutableArray *array = self.myImageArray;
[tapBlockView setTapBlock:^(UIImage* image) {
[array addObject:image]; // If I will do this then how will I update original Array ?
}
I have also tried
__weak id weakSelf = self;
[tapBlockView setTapBlock:^(UIImage* image) {
[weakSelf storeImageInaNewMethod:image]; // Calling SToreImageInaNewMethod
}
and
-(void)storeImageInaNewMethod:(UIImage*)image {
[self.myImageArray addObject:image]; // This again retaining cycle
}
What is the proper way to update original object defined by property ?
After maddy's answer - this is from 2012 WWDC lecture on GCD and asynchronous programming:
__weak MyClass *weakSelf = self;
[tapBlockView setTapBlock:^(UIImage* image) {
__strong MyClass *strongSelf = weakSelf;
if(strongSelf) {
[strongSelf.myImageArray addObject:image];
}
}];
Try a combination of the 2nd and 3rd.
__weak id weakSelf = self;
[tapBlockView setTapBlock:^(UIImage* image) {
[weakSelf.myImageArray addObject:image];
}
In your case you only need to reference an array which is referenced by self, so:
NSMutableArray *array = self.myImageArray;
[tapBlockView setTapBlock:^(UIImage* image)
{
[array addObject:image]; // No cycle
}];
Works fine provided that self.myImageArray does not return different array references at different times. There is no cycle: the current object references the array and the block, and in turn the block references the array.
If self.myImageArray does return different array references as different times then use a weak reference to self, your case 3.
Your second and third ones appear correct. The second one works because you did not create a copy of the array, so that still points to the original one. The third one works because the reference to self is weak.
I have a object derived from UIView, it is AIItem, this item have UIImageView *status_view, now I need another object AIAnotherItem derived from AIItem, problem is in status_view.
For Example :
AIItem init method
-(id)initWithName:(NSString *)name {
self = [super init];
if (self) {
status_view = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,50,50)];
status_view.image = [UIImage imageNamed:#"item_image.png"];
[self addSubview:status_view];
}
}
AIAnotherItem init method
-(id)initWithName:(NSString *)name {
self = [super initWithName:name];
if (self) {
status_view.image = [UIImage imageNamed:#"another_item_image.png"];
}
return self;
}
in AIAnotherItem I set another image to status_view but it won't changed.
Question is why ? and how do this ?
Regardless what the mechanics are of this not working (I am sure you will figure it out), I believe that you are perhaps not going about this the right way.
Would it not be more logical to have class AIItem.h that has an empty property statusView? And then two derived classes (or instances of the same subclass) that inherit the same statusView but fill it with different images?
I think this would correspond more closely to the philosophy behind inheritance.
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.
I'm having a bit of an issue with holding a mixture of a custom class and UIImage views in an array. These are stored in the array and I'm using:
if ([[fixtures objectAtIndex:index] isKindOfClass:[Fixture class]])
to distinguish between if it's a UIIMage or Fixture object. My source code for this is:
- (void) moveActionGestureRecognizerStateChanged: (UIGestureRecognizer *) recognizer
{
switch ( recognizer.state )
{
case UIGestureRecognizerStateBegan:
{
NSUInteger index = [fixtureGrid indexForItemAtPoint: [recognizer locationInView: fixtureGrid]];
emptyCellIndex = index; // we'll put an empty cell here now
// find the cell at the current point and copy it into our main view, applying some transforms
AQGridViewCell * sourceCell = [fixtureGrid cellForItemAtIndex: index];
CGRect frame = [self.view convertRect: sourceCell.frame fromView: fixtureGrid];
dragCell = [[FixtureCell alloc] initWithFrame: frame reuseIdentifier: #""];
if ([[fixtures objectAtIndex:index] isKindOfClass:[Fixture class]]) {
Fixture *newFixture = [[Fixture alloc] init];
newFixture = [fixtures objectAtIndex:index];
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
[newFixture release];
} else {
dragCell.icon = [fixtures objectAtIndex: index];
}
[self.view addSubview: dragCell];
}
}
However, when dragging the cell that was an object of class Fixture, I would get errors such as EXC_BAD_ACCESS or unrecognized selector sent to instance (which makes sense as it was sending a CALayerArray a scale command.
I therefore set a breakpoint to see inside the fixtures array. Here I saw that the UIImages were all set to the right class type but there was also:
(CALayerArray *)
(Fixture *)
(NSObject *)
for the positions were the Fixture classes were being held in the array. Could anyone shed some light onto why it's doing this? If you need any more info to help please feel free to ask.
Denis
In your code here:
Fixture *newFixture = [[Fixture alloc] init];
newFixture = [fixtures objectAtIndex:index];
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
[newFixture release];
It looks like you're releasing an autorelease object (newFixture). When you get an object out of the array, it's autorelease.
You also have a memory leak, when you allocate the newFixture at the first line, that object is never released because you replace the pointer to it in your 2nd line.
Fixture *newFixture = [[Fixture alloc] init]; // THIS OBJECT IS NEVER RELEASED
newFixture = [fixtures objectAtIndex:index]; // YOU'RE REPLACING THE newFixture POINTER WITH AN OBJECT FROM THE ARRAY
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
[newFixture release]; // YOU'RE RELEASING AN AUTORELEASED OBJECT
So the code should be like
Fixture *newFixture = [fixtures objectAtIndex:index];
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
Then your property should retain the image correctly.
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]]