I built an app that when a textview was filled in, the keyboard would pop up and allow you to type. If I decided that I didn't want the keyboard up, I could tap the background view controller and it would fall away. Now, I added a scrollview. Everything works fine, but I cannot get the actions to connect and make the keyboard fall away when touching outside the textview.
(I cannot make a custom view controller in Xcode)
Does anyone have any fixes?
Thank you in advance!
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITextField *actionField;
#property (weak, nonatomic) IBOutlet UITextField *impactField;
#property (weak, nonatomic) IBOutlet UITextField *resultField;
#end
#implementation ViewController
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager]
fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc]
initWithContentsOfFile:filePath];
for (int i = 0; i < 3; i++) {
UITextField *theField = self.lineFields [i];
theField.text = array [i];
}
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:#selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
}
- (void)applicationWillResignActive:
(NSNotification *)notification
{
NSString *filePath = [self
dataFilePath];
NSArray *array = [self.lineFields valueForKey:#"text"];
[array writeToFile:filePath atomically:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)textFieldDoneEditing:(id)sender {
[sender resignFirstResponder];
}
- (IBAction)backgroundTap: (id)sender {
[self.actionField resignFirstResponder];
[self.impactField resignFirstResponder];
[self.resultField resignFirstResponder];
}
Try UITapGestureRecognizer:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapScrollView:)];
[scrollView addGestureRecognizer:singleTap];
and for the action:
- (void)tapScrollView:(UITapGestureRecognizer *)gesture {
[self.actionField resignFirstResponder];
[self.impactField resignFirstResponder];
[self.resultField resignFirstResponder];
}
Related
I've literally tried everything. I'm sure my mistake is going to be something as stupid and small as a missed self.string, but I can't seem to get it working. What my mini program does is checks if a file named Code.txt already exists. If it does exist, then it will load the file in a UITextView (and it does this just fine). If it doesn't exist, it will create a file name Code.txt. All of this works just fine.
However, when I try to save the current text inside the UITextView to the file, I am unable to save it to the string first. This is what I am trying to achieve:
Upon exiting the app: textView.text --> codeString --> Code.txt [saved]
Except, again, I am unable to save the textView.text to the string (codeString). The NSLog is returning it as a nut (see NSLog(#"String: %#", self.codeString); in the saveFile method).
ViewController.h
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "BuildViewController.h"
#interface ViewController : UIViewController <UITextViewDelegate>
#property (nonatomic, strong) NSString *codeString;
#property (nonatomic, retain) IBOutlet UITextView *textView;
#property (nonatomic, retain) BuildViewController *buildViewController;
- (void)saveFile;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize textView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
textView.delegate = self;
// Check if Code.txt exists
NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *codeFile = [NSString stringWithFormat:#"%#/Code.txt", documentsDir];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:codeFile];
NSLog(#"viewWillAppear");
if (fileExists == true) {
// Code.txt does exist, continue to viewDidLoad
NSLog(#"Code.txt does exist");
}
else if (fileExists == false) {
// Code.txt does not exist, create the file
NSLog(#"Code.txt does not exist");
ViewController *viewController = [ViewController alloc];
[viewController createFile];
}
self.textView.delegate = self;
}
- (void)viewWillAppear:(BOOL)animated {
// Load Code.txt
NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* codeFile = [documentsDir stringByAppendingPathComponent:#"Code.txt"];
NSString *codeString = [NSString stringWithContentsOfFile:codeFile encoding:NSUTF8StringEncoding error:NULL];
textView.text = codeString;
NSLog(#"Loaded Code.txt");
}
- (void)saveFile {
// Save text to Code.txt
self.codeString = textView.text;
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *codeFile = [NSString stringWithFormat:#"%#/Code.txt", documentsDir];
[self.codeString writeToFile:codeFile
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSLog(#"String: %#", self.codeString);
NSLog(#"Saved text to Code.txt");
}
- (void)createFile {
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *codeFile = [NSString stringWithFormat:#"%#/Code.txt", documentsDir];
NSString *codeString = #"print(\"Hello, world\")";
[codeString writeToFile:codeFile
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSLog(#"Created Code.txt");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Your error is you create a new instance of ViewController like #Avi said.
You should get the existing instance in memory
If you want to save file when in background,you may register notification
In viewDidLoad,add this line
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(enterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
Then add this function to ViewController
-(void)enterBackground:(NSNotification *)notification{
[self saveFile];
}
Then in dealloc
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}
I have some UISwitches and I want to load their states from a .plist file. I've tried countless times but it seems not to be working. This is my code:
-(void) loadVariables {
NSMutableDictionary *dictionary;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:#"Settings.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"plist"];
NSLog(#"NOT FOUND%#",plistPath);
}
dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[[Settings sharedInstance] setMobileSwitch:[[dictionary objectForKey:#"mobileSwitch"]boolValue]];
[[Settings sharedInstance] setEmailSwitch:[[dictionary objectForKey:#"emailSwitch"]boolValue]];
[[Settings sharedInstance] setLocationSync:[[dictionary objectForKey:#"locationSync"]boolValue]];
[[Settings sharedInstance] setCaptureLocation:[[dictionary objectForKey:#"captureLocation"]boolValue]];
[self.mobileSwitchButton setOn:[[dictionary objectForKey:#"mobileSwitch"]boolValue]];
[self.emailSwitchButton setOn:[[dictionary objectForKey:#"emailSwitch"]boolValue]];
[self.locationSyncButton setOn:[[dictionary objectForKey:#"locationSync"]boolValue]];
[self.captureLocationButton setOn:[[dictionary objectForKey:#"captureLocation"]boolValue]];
}
For some reason when I call it in my viewDidLoad method like [self.mobileSwitchButton setOn:1]; it works. What am I doing wrong?
In NSLog my dictionary prints the following:
dictionary {
captureLocation = 0;
emailSwitch = 1;
locationSync = 1;
mobileSwitch = 0;
}
In my ViewDidLoad method:
- (void)viewDidLoad
{
[super viewDidLoad];
[mobileSwitchButton addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
[emailSwitchButton addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
[locationSyncButton addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
[captureLocationButton addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
[[Settings sharedInstance] loadVariables];
}
In my .h file I also have this:
//Switches
#property (retain, nonatomic) IBOutlet UISwitch *mobileSwitchButton;
#property (retain, nonatomic) IBOutlet UISwitch *emailSwitchButton;
#property (retain, nonatomic) IBOutlet UISwitch *locationSyncButton;
#property (retain, nonatomic) IBOutlet UISwitch *captureLocationButton;
In my implementation file I also have this:
+(Settings *)sharedInstance {
static Settings *myInstance = nil;
// check to see if an instance already exists
if (nil == myInstance) {
myInstance = [[[self class] alloc] init];
}
// return the instance of this class
return myInstance;
}
I'm calling my loadVariables method in my ViewDidLoad method and I'm trying to change the state of my UISwitch in my loadVariables method. If I do place the code for changing the UISwitch state in the ViewDidLoad it works. But the code doesn't seem to execute from my [[Settings sharedInstance] loadVariables] method.
Have you tried setting the switches in viewWillAppear? That seems to me the most appropriate place.
Also, there seem to be two instances of your loadVariables method. The singleton cannot / should not contain the switches. But in viewDidLoad you call the singleton's method. This might be part of your problem. Get the values from your singleton and set the in the view controller.
Presumably dictionary is nil, or it doesn't contain any object for the key you are giving.
Do you execute this code when your views have been already created? If you do it prior to viewDidLoad call, your switches may be equal to nil, and therefore your code won't change their state.
Here is my mainAppDelegate.h:
#import <UIKit/UIKit.h>
#interface mainAppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property NSMutableArray *toDoItems;
#end
and my mainAppDelegate.m:
#import "mainAppDelegate.h"
#implementation mainAppDelegate
- (void)applicationWillTerminate:(UIApplication *)application
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"toDoItems.plist"];
[self.toDoItems writeToFile:filePath atomically:TRUE];
}
#end
I have another file, XYZToDoListViewController.m with the code:
#import "XYZToDoListViewController.h"
#import "XYZToDoItem.h"
#import "XYZAddItemViewController.h"
#interface XYZToDoListViewController ()
#property NSMutableArray *toDoItems;
#end
#implementation XYZToDoListViewController
- (IBAction)unwindToList:(UIStoryboardSegue *)segue
{
XYZAddItemViewController *source = [segue sourceViewController];
XYZToDoItem *item = source.toDoItem;
if (item != nil) {
[self.toDoItems addObject:item];
[self.tableView reloadData];
}
}
- (IBAction)clearData:(UIBarButtonItem *)sender;
{
[self.toDoItems removeAllObjects];
[self.tableView reloadData];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.toDoItems = [[NSMutableArray alloc] init];
self.navigationController.view.backgroundColor =
[UIColor colorWithPatternImage:[UIImage imageNamed:#"bg_full.png"]];
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, -35, 0);
}
#end
This is at least what I think is relevant. My basic framework is something I followed from this tutorial. So as you can see I have an NSMutableArray named .toDoItems. and I want it to remember the list when I exit the application (not just minimizing it; it does that already. I think I have the code which is saving the data, but what do I use to check if the file exists, and if so, display it?
And would this affect my clearData method when the app resumes as well?
As if i understood true you want to save your NSMutableArray even after restart your app.
So you may use this codes to save your NSMutableArray with NSUserDefaults.
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaultsPhoneId setObject:yourArray forKey:#"yourKey"];
[defaultsPhoneId synchronize];
And it is how you can take it back
yourArray=[[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:#"yourKey"]];
But dont forget to initialize it before save with NSUserDefaults.
By the way you may check yourArray anytime if it is loaded or not with
if([yourArray count]==0){
//Your array is empty so you have to call it with #"yourKey". (second codes part)
}
"what do I use to check if the file exists"
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:your_file_path])
"..and if so, display it?"
Please read about UITableView and UITableViewDataSource
https://developer.apple.com/library/ios/documentation/uikit/reference/UITableView_Class/Reference/Reference.html
"And would this affect my clearData method when the app resumes as well?"
clearData is a button action. It will be called only if user will tap
a button. It is not connected with application launch/stopping.
I want to make a synchronized show lyric app and all lyric shown on a UITextView. In order to highlight current lyric I add background color to NSAttributedString of UITextView. All NSRange of lines stored in a NSArray.
My code is pretty simple, when button tapped move the highlight line down (via set contentOffset of UITextView). But here a strange problem occurred. In the beginning, the UITextView scroll properly but when contentOffset of UITextView greater then its frame.size.height it was fixed.
Here is my code:
//View controller
#import "ViewController.h"
#interface ViewController () {
NSUInteger globelIndex;
NSArray *textRanges;
NSMutableAttributedString *attributedText;
}
#property (weak, nonatomic) IBOutlet UITextView *lyricView;
#property (strong, nonatomic) NSTimer *mainTimer;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *rawText = [self readFile];
globelIndex = 0;
[self initTextLines:rawText];
attributedText = [[NSMutableAttributedString alloc] initWithString:rawText
attributes:#{NSBackgroundColorAttributeName: [UIColor orangeColor]}];
self.lyricView.attributedText = [attributedText copy];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)manualNextLine:(UIButton *)sender {
[self updateTextView];
}
- (IBAction)autoNextLineUsingNSTimer:(UIButton *)sender {
self.mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateTextView) userInfo:nil repeats:YES];
}
- (void)updateTextView {
if (self.lyricView.contentOffset.y >= self.lyricView.contentSize.height &&
self.mainTimer)
{
self.mainTimer = nil;
return;
}
NSMutableAttributedString *mat = [attributedText mutableCopy];
NSValue *value = [textRanges objectAtIndex:globelIndex];
[mat addAttribute:NSBackgroundColorAttributeName value:[UIColor whiteColor] range:[value rangeValue]];
self.lyricView.attributedText = [mat copy];
globelIndex += 1;
// self.textView.contentOffset = CGPointMake(self.textView.contentOffset.x, self.textView.contentOffset.y + 24);
// [self.textView scrollRangeToVisible:[value rangeValue]];
CGPoint newOffset = CGPointMake(self.lyricView.contentOffset.x, self.lyricView.contentOffset.y + 20);
[self.lyricView setContentOffset:newOffset animated:NO];
NSLog(#"[%# %#] h: %f b: %f a: %f", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.lyricView.contentSize.height, newOffset.y, self.lyricView.contentOffset.y);
}
#pragma mark - helper
- (void)initTextLines:(NSString *)rawText {
NSMutableArray *result = [#[] mutableCopy];
NSArray *t = [rawText componentsSeparatedByString:#"\r\n"];
__block int index = 0;
[t enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *s = obj;
NSRange range = NSMakeRange(index, s.length + 2);
[result addObject:[NSValue valueWithRange:range]];
index += s.length + 2;
}];
textRanges = [result copy];
}
- (NSString *)readFile {
NSError *error = nil;
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:#"二人の季節が-ささきのぞみ-想い" withExtension:#"lrc"];
NSString *content = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&error];
if (error) {
if (DEBUG) NSLog(#"[%# %#] Error: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
abort();
}
return content;
}
#end
All my code was in ViewController and StoryBoard has two UIButton and a UITextView.
What I wonder is "Why the UITextView.contentOffset cannot change when it greater than some size".
Maybe rewrite setContentOffset:animated is helpful for you!
Here is some sample code which you can borrow:
https://github.com/360/Three20/blob/master/src/Three20UI/Sources/TTTextView.m
#import "Three20UI/TTTextView.h"
// UI
#import "Three20UI/UIViewAdditions.h"
#implementation TTTextView
#synthesize autoresizesToText = _autoresizesToText;
#synthesize overflowed = _overflowed;
- (void)setContentOffset:(CGPoint)offset animated:(BOOL)animated {
if (_autoresizesToText) {
if (!_overflowed) {
// In autosizing mode, we don't ever allow the text view to scroll past zero
// unless it has past its maximum number of lines
[super setContentOffset:CGPointZero animated:animated];
} else {
// If there is an overflow, we force the text view to keep the cursor at the bottom of the
// view.
[super setContentOffset: CGPointMake(offset.x, self.contentSize.height - self.height)
animated: animated];
}
} else {
[super setContentOffset:offset animated:animated];
}
}
#end
i am developing very simple quiz app
In viewDidLoad i am adding objects in myarray
where ever i nslog myarray values it works fine
but if i try this inside ibaction methods all objects becomes zombie
for 2 days i am stuck in this but can't find it what is wrong.
quiz.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#class dbVals;
#class viewTransition;
#class AppDelegate;
#interface quiz : UIViewController
{
NSMutableArray *myarray;
IBOutlet UITextView *questionTextView_;
IBOutlet UIButton *skipButton_;
IBOutlet UIButton *optionAButton_;
IBOutlet UIButton *optionBButton_;
IBOutlet UIButton *optionCButton_;
NSString *correctAnswer;
int questionNumber;
int score;
IBOutlet UILabel *scoreLabel_;
int totalQuestions;
}
-(void)populate:(int)number;
//#property(nonatomic, retain) NSMutableArray *myarray;
#property (retain, nonatomic) IBOutlet UITextView *questionTextView;
#property (retain, nonatomic) IBOutlet UIButton *skipButton;
#property (retain, nonatomic) IBOutlet UIButton *optionAButton;
#property (retain, nonatomic) IBOutlet UIButton *optionBButton;
#property (retain, nonatomic) IBOutlet UIButton *optionCButton;
#property (retain, nonatomic) IBOutlet UILabel *scoreLabel;
- (IBAction)optionsToAnswer:(id)sender;
- (IBAction)zzz:(id)sender;
#end
quiz.m
#import "quiz.h"
#import "DbVals.h"
#import "viewTransition.h"
#import "AppDelegate.h"
#implementation quiz
#synthesize skipButton=skipButton_;
#synthesize optionAButton=optionAButton_;
#synthesize optionBButton=optionBButton_;
#synthesize optionCButton=optionCButton_;
#synthesize scoreLabel=scoreLabel_;
#synthesize questionTextView=questionTextView_;
//#synthesize myarray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)createEditableCopyOfDatabaseIfNeeded
{
//NSLog(#"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
+(sqlite3 *) getNewDBConnection
{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
//NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
- (void)viewDidLoad
{
[super viewDidLoad];
questionNumber = 0;
score = 0;
[self createEditableCopyOfDatabaseIfNeeded];
sqlite3 *dbc = [quiz getNewDBConnection];
sqlite3_stmt *statement = nil;
const char *sqlSelect = "select * from QnA ORDER BY RANDOM()";
if(sqlite3_prepare_v2(dbc, sqlSelect, -1, &statement, NULL)!=SQLITE_OK)
{
NSAssert1(0, #"Error Preparing Statement", sqlite3_errmsg(dbc));
}
else
{
myarray = [[NSMutableArray alloc]init];
while(sqlite3_step(statement)==SQLITE_ROW)
{
NSString *q = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
NSString *o = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
NSString *a = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 2)];
DbVals *dbValsObj = [[DbVals alloc]init];
[dbValsObj setValsOfQuestions:q options:o answer:a];
[myarray addObject:dbValsObj];
[dbValsObj release];
}
}
sqlite3_finalize(statement);
//[self populate:questionNumber];
}
-(void)populate:(int)number
{
/*[scoreLabel_ setText:[NSString stringWithFormat:#"%d",score]];
AppDelegate *appDel = [[UIApplication sharedApplication] delegate];
[appDel setFinalScore:[NSString stringWithFormat:#"%d",score]];
if(number < [myarray count])
{
DbVals *dbv1 = [myarray objectAtIndex:number];
[questionTextView_ setText:[dbv1 getQuestions]];
NSString *joinedOptions = [dbv1 getOptions];
NSArray *splitOptions = [joinedOptions componentsSeparatedByString:#","];
[optionAButton_ setTitle:[splitOptions objectAtIndex:0] forState:UIControlStateNormal];
[optionBButton_ setTitle:[splitOptions objectAtIndex:1] forState:UIControlStateNormal];
[optionCButton_ setTitle:[splitOptions objectAtIndex:2] forState:UIControlStateNormal];
correctAnswer = [dbv1 getAnswer];
}
else
{
//viewTransition *vt = [[viewTransition alloc]init];
[viewTransition viewsTransitionCurrentView:self toNextView:#"result"];
//[vt release];
}*/
}
- (void)viewDidUnload
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<u><u><u><u><><><><><><><><><><><>");
}
[self setQuestionTextView:nil];
[questionTextView_ release];
questionTextView_ = nil;
[self setQuestionTextView:nil];
[skipButton_ release];
skipButton_ = nil;
[self setSkipButton:nil];
[optionAButton_ release];
optionAButton_ = nil;
[self setOptionAButton:nil];
[optionBButton_ release];
optionBButton_ = nil;
[self setOptionBButton:nil];
[optionCButton_ release];
optionCButton_ = nil;
[self setOptionCButton:nil];
[scoreLabel_ release];
scoreLabel_ = nil;
[self setScoreLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<d><d><d><d><d><><><><><><><><><><>");
}
[questionTextView_ release];
[skipButton_ release];
[optionAButton_ release];
[optionBButton_ release];
[optionCButton_ release];
[scoreLabel_ release];
[myarray release];
[super dealloc];
}
- (IBAction)optionsToAnswer:(id)sender
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"six");
}
if(sender == skipButton_)
{
//questionNumber++;
//[self populate:questionNumber];
/*[UIView animateWithDuration:5 delay:0 options: UIViewAnimationCurveEaseOut
animations:
^{
[UIView setAnimationTransition:103 forView:self.view cache:NO];
}
completion:
^(BOOL finished)
{
}
];*/
}
if(sender == optionAButton_)
{
/*NSString *one = #"1";
if([correctAnswer isEqualToString:one])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionBButton_)
{
/*NSString *two = #"2";
if([correctAnswer isEqualToString:two])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionCButton_)
{
/*NSString *three = #"3";
if([correctAnswer isEqualToString:three])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
}
- (IBAction)zzz:(id)sender
{
}
#end
dbVals.h
#import <Foundation/Foundation.h>
#interface DbVals : NSObject
{
NSString *questions_;
NSString *options_;
NSString *answer_;
// NSString *hint;
// NSString *mode;
}
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer;
-(NSString*)getQuestions;
-(NSString*)getOptions;
-(NSString*)getAnswer;
dbVals.m
#import "DbVals.h"
#implementation DbVals
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
questions_ = questions;
options_ = options;
answer_ = answer;
}
-(NSString*)getQuestions
{
return questions_;
}
-(NSString*)getOptions
{
return options_;
}
-(NSString*)getAnswer
{
return answer_;
}
#end
Your dbVals.m setVals isn't retaining the parameters. This obviously means, everything inside becomes deallocated once the function scope ends.
Try changing it to something like
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
[questions_ release];
[options_ release];
[answer_ release];
questions_ = [questions copy];
options_ = [options copy];
answer_ = [answer copy];
}