Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Sergio10

macrumors regular
Original poster
Oct 3, 2007
137
0
Hi,

I developed category for UIImageView:
PHP:
- (NSInteger) val
{
	return val;
}
- (void) setVal: (NSInteger)myValue
{
	val = myValue
}
And then create 3 images. Set ONLY one setVal with "123". And add to NSArray
PHP:
NSMutableArray *myArray = [[NSMutableArray alloc]init];

UIImageView *view1 =  [[UIImageView alloc] initWithFrame: CGRectMake(0.0, 0.0, 10, 10)];
[view1 setVal: 123];
[myArray addObject: view1];
UIImageView *view2 =  [[UIImageView alloc] initWithFrame: CGRectMake(10.0, 0.0, 10, 10)];
[myArray addObject: view2];
UIImageView *view3 =  [[UIImageView alloc] initWithFrame: CGRectMake(20.0, 0.0, 10, 10)];
[myArray addObject: view3];

for(int a=0; a<[myArray count]; a++)
{
   UIImageview *view = [myArray objectAtIndex: a];
   NSLog(@"Object: %d : %d", a, [view val]);
}
So , I get "123" value for all images. WHY? What is wrong???
Thanks
 
Here is an interface
PHP:
@interface UIImageView (myCat)

NSInteger val;

- (NSInteger) val;
- (void) setVal: (NSInteger)some;

@end
 
Note that a category can’t declare additional instance variables for the class; it includes only methods.

And how it works in my code?
PHP:
@interface UIImageView (MyCat)
NSString *title;

- (void) setTitle: (NSString*) labelText: (NSInteger) fontSize: (UIColor*) textColor;
- (NSString*) title;
@end

.........

@implementation UIImageView (MyCat)

- (void) setTitle: (NSString*) labelText: (NSInteger) fontSize: (UIColor*) textColor
{	
	title = labelText;
	CGRect frame = [self frame];
	frame.origin.x = 0;
	frame.origin.y = 0;

	NSArray *subArray = [self subviews];
	if([subArray count] > 0)		// if label allready exist just change text
	{
		UILabel *label = [subArray lastObject];
		[label setFont:[UIFont systemFontOfSize: fontSize]];
		label.textAlignment = UITextAlignmentCenter;
		[label setText: labelText];
		label.textColor = textColor;
		label.backgroundColor = [UIColor clearColor];		
	}
	else	// create new label
	{
		UILabel *label = [[UILabel alloc] initWithFrame: frame];
		[label setFont:[UIFont systemFontOfSize: fontSize]];
		label.textAlignment = UITextAlignmentCenter;
		[label setText: labelText];
		label.textColor = textColor;
		label.backgroundColor = [UIColor clearColor];
		
		[self addSubview: label];		
	}	
}

- (NSString*) title
{
	return title;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.