我正在使用 iCarousel
制作老虎机应用程序,我的 iCarousel
包含来自 NSDocumentDirectory
的图像,该图像来 self 的 ImagePicker
。这就是我的应用程序的工作原理,当用户按下按钮时,iCarousel
就会旋转。
当它停止时,显示该项目 3 秒,然后将其删除。
我的问题是当我转到另一个 View 时,已删除的索引/项目又出现了。即使我进入不同的 View ,如何维护我的数组。删除的索引/项目不会显示,只有在应用程序重新启动之前才会显示,就像保存数组一样。感谢您的帮助。
//我的数组
- (void)viewDidLoad
{
self.images = [NSMutableArray new];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[images addObject:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
}
- (void)viewWillAppear:(BOOL)animated {
spinButton = [UIButton buttonWithType:UIButtonTypeCustom];
[spinButton addTarget:self action:@selector(spin) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:spinButton];
}
- (void) carouselDidEndScrollingAnimation:(iCarousel *)carousel{
[NSTimer scheduledTimerWithTimeInterval:0.56 //this arranges the duration of the scroll
target:self
selector:@selector(deleteItem)
userInfo:nil
repeats:NO];
}
//旋转和删除方法
- (void)spin {
[carousel scrollByNumberOfItems:-35 duration:10.7550f];
}
-(void) deleteItem {
//Removes the object chosen
NSInteger index = carousel.currentItemIndex;
[carousel removeItemAtIndex:index animated:YES];
[images removeObjectAtIndex:index];
}
我需要的是,当索引/项目被删除时,即使我转到其他 View ,它也不会暂时显示。仅当应用程序关闭并再次打开后, View 才会重新启动
最佳答案
您的问题是您每次进入 View 时都会创建图像NSMutableArray
。
正如@Saleh所说,你应该将数组放置在 View Controller 之外。要在 appDelegate
中执行此操作,就像他建议的那样,请执行以下操作:
在AppDelegate.h中声明:
@property( strong, nonatomic) NSMutableArray *images;
在AppDelegate.m中:
@synthesize images;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Read the images after the existing code ....
self.images = [NSMutableArray array];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[images addObject:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
return YES;
}
然后在您的ViewController.m中:
#import "AppDelegate.h"
并更改您的viewDidLoad
方法:
- (void)viewDidLoad
{
[super viewDidLoad];
self.images = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).images;
}
这应该有效。
关于iphone - NSMutableArray 索引删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11183270/