Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CoreDataDemo.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
TargetAttributes = {
9B71A4121F9BE73000E8ADE6 = {
CreatedOnToolsVersion = 9.0;
LastSwiftMigration = 1140;
ProvisioningStyle = Automatic;
};
};
Expand Down Expand Up @@ -283,7 +284,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = shashi.CoreDataDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.0;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
Expand All @@ -297,7 +298,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = shashi.CoreDataDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.0;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
Expand Down
2 changes: 1 addition & 1 deletion CoreDataDemo/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
Expand Down
85 changes: 81 additions & 4 deletions CoreDataDemo/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
@@ -1,24 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" systemVersion="17A277" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16096" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="target" sceneMemberID="viewController">
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="CoreDataDemo" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="XwQ-oR-wa6">
<rect key="frame" x="54" y="579" width="284" height="21"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Cqd-gx-O0o">
<rect key="frame" x="54" y="608" width="284" height="21"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="UsV-2a-qXB">
<rect key="frame" x="54" y="637" width="284" height="21"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<textField opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="tMu-GF-OAe">
<rect key="frame" x="54" y="189" width="284" height="34"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<textField opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="8wa-Cz-7cF">
<rect key="frame" x="54" y="231" width="284" height="34"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" secureTextEntry="YES"/>
</textField>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="2vZ-Mv-Rng">
<rect key="frame" x="172" y="475" width="49" height="30"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<state key="normal" title="Submit"/>
<connections>
<action selector="submitAction:" destination="BYZ-38-t0r" eventType="touchUpInside" id="ZHC-3J-7rD"/>
</connections>
</button>
<datePicker contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" datePickerMode="date" style="wheels" translatesAutoresizingMaskIntoConstraints="NO" id="58R-cr-at2">
<rect key="frame" x="-11" y="281" width="414" height="186"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMaxY="YES"/>
</datePicker>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="QKE-JB-ASL">
<rect key="frame" x="175" y="144" width="36" height="30"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<state key="normal" title="Clear"/>
<connections>
<action selector="clearDataBase:" destination="BYZ-38-t0r" eventType="touchUpInside" id="34M-m9-3jm"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Mma-RZ-bpq">
<rect key="frame" x="177" y="521" width="39" height="30"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<state key="normal" title="Fetch"/>
<connections>
<action selector="fetchAction:" destination="BYZ-38-t0r" eventType="touchUpInside" id="ivy-bO-BPL"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
<connections>
<outlet property="ageLabel" destination="UsV-2a-qXB" id="mba-wt-rkj"/>
<outlet property="clearButton" destination="QKE-JB-ASL" id="ljK-yU-RSd"/>
<outlet property="dobPicker" destination="58R-cr-at2" id="bgm-Ra-x0H"/>
<outlet property="enterName" destination="tMu-GF-OAe" id="YM5-PE-mwZ"/>
<outlet property="enterPassword" destination="8wa-Cz-7cF" id="COq-vI-xqa"/>
<outlet property="fetchButton" destination="Mma-RZ-bpq" id="QPq-BA-Xu8"/>
<outlet property="nameLabel" destination="XwQ-oR-wa6" id="A1o-KT-mQg"/>
<outlet property="passwordLabel" destination="Cqd-gx-O0o" id="qMU-6v-y9L"/>
<outlet property="submitButton" destination="2vZ-Mv-Rng" id="8Z0-fJ-kbU"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="137.68115942028987" y="115.84821428571428"/>
</scene>
</scenes>
</document>
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="13240" systemVersion="" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="16119" systemVersion="19E287" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="Users" representedClassName="Users" syncable="YES" codeGenerationType="class">
<attribute name="age" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="password" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="username" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="age" optional="YES" attributeType="String"/>
<attribute name="password" optional="YES" attributeType="String"/>
<attribute name="username" optional="YES" attributeType="String"/>
</entity>
<elements>
<element name="Users" positionX="-63" positionY="-18" width="128" height="90"/>
<element name="Users" positionX="-63" positionY="-18" width="128" height="88"/>
</elements>
</model>
104 changes: 79 additions & 25 deletions CoreDataDemo/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,54 +10,108 @@ import UIKit
import CoreData

class ViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var clearButton: UIButton!
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var fetchButton: UIButton!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var dobPicker: UIDatePicker!
@IBOutlet weak var enterPassword: UITextField!
@IBOutlet weak var enterName: UITextField!

// MARK: overrides
override func viewDidLoad() {
super.viewDidLoad()

fetchButton.isEnabled = false
submitButton.isEnabled = false

[enterPassword, enterName, dobPicker].forEach({ $0.addTarget(self, action: #selector(editingChanged), for: .editingChanged) })

// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: Field Actions

@objc func editingChanged(_ textField: UITextField) {
if textField.text?.count == 1 {
if textField.text?.first == " " {
textField.text = ""
return
}
}
guard
let name = enterName.text, !name.isEmpty,
let password = enterPassword.text, !password.isEmpty
else {
submitButton.isEnabled = false
return
}
submitButton.isEnabled = true

}

@IBAction func submitAction(_ sender: UIButton) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate

let context = appDelegate.persistentContainer.viewContext

let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)


newUser.setValue("Shashikant", forKey: "username")
newUser.setValue("1234", forKey: "password")
newUser.setValue("12", forKey: "age")


newUser.setValue(enterName.text, forKey: "username")
newUser.setValue(enterPassword.text, forKey: "password")
let date = Date()
let calendar = Calendar.current
_ = calendar.component(.hour, from: date)
_ = calendar.component(.minute, from: date)

let age = calendar.dateComponents([.year], from: date, to: dobPicker.date)
print("age in years =\(String(describing: abs(age.year!)))")
newUser.setValue(String(abs(age.year!)), forKey: "age")
do {

try context.save()

fetchButton.isEnabled = true
} catch {

print("Failed saving")
}

}

@IBAction func clearDataBase(_ sender: UIButton) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Users")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
let context = appDelegate.persistentContainer.viewContext

do {
try context.execute(deleteRequest)
clearButton.isEnabled = false
} catch let error as NSError {
// TODO: handle the error
print(error)
}
}
@IBAction func fetchAction(_ sender: UIButton) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//request.predicate = NSPredicate(format: "age = %@", "12")
request.returnsObjectsAsFaults = false

do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "username") as! String)
nameLabel.text = (data.value(forKey: "username") as! String)
passwordLabel.text = (data.value(forKey: "password") as! String)
ageLabel.text = (data.value(forKey: "age") as! String)
}

} catch {

print("Failed")
}

// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}